opencode-swarm 7.146.1 → 7.146.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.
- package/dist/cli/{config-doctor-sd7x5bts.js → config-doctor-vstrprja.js} +2 -2
- package/dist/cli/{core-17febkvw.js → core-3wzpwe5z.js} +1 -1
- package/dist/cli/{curator-vghf320v.js → curator-cvy1s7wd.js} +17 -17
- package/dist/cli/{curator-llm-factory-zxbgkjm5.js → curator-llm-factory-6bra0bfd.js} +17 -17
- package/dist/cli/{evidence-summary-service-xma4aagr.js → evidence-summary-service-yhap2xph.js} +6 -6
- package/dist/cli/{gate-evidence-2bznvee8.js → gate-evidence-vxbyq5sb.js} +2 -2
- package/dist/cli/{guardrail-explain-ppzg0xz9.js → guardrail-explain-h8cnwa02.js} +18 -18
- package/dist/cli/{guardrail-log-xexwz93q.js → guardrail-log-syb7tz2w.js} +3 -3
- package/dist/cli/{hive-promoter-j3vw2hj4.js → hive-promoter-3tex870c.js} +17 -17
- package/dist/cli/{index-1c9mfnj0.js → index-01ybcsa5.js} +1 -1
- package/dist/cli/{index-vacrzesw.js → index-42nq97rb.js} +4 -4
- package/dist/cli/{index-zwn2e2pe.js → index-46cypnz3.js} +2 -2
- package/dist/cli/{index-twwb61bh.js → index-4vwn66wk.js} +3 -3
- package/dist/cli/{index-va8a2zrq.js → index-a1febb2k.js} +2 -2
- package/dist/cli/{index-xz0ccakc.js → index-c9jr4j2q.js} +1 -1
- package/dist/cli/{index-k46kg4t6.js → index-cr90rcg3.js} +3 -3
- package/dist/cli/{index-tzyvmkd1.js → index-cx67qa9g.js} +1 -1
- package/dist/cli/{index-bd4g9fvb.js → index-f3x2gsby.js} +1 -1
- package/dist/cli/{index-9qbr27bw.js → index-jv9xs6mb.js} +1 -1
- package/dist/cli/{index-cw96tpy6.js → index-n4k0pt5f.js} +1 -1
- package/dist/cli/{index-g8qbjqqz.js → index-p0m03xa6.js} +1 -1
- package/dist/cli/{index-e3caa7ng.js → index-r46q6996.js} +19 -19
- package/dist/cli/{index-7x00nx8m.js → index-rfph0nhf.js} +45 -45
- package/dist/cli/{index-t7sfrv3v.js → index-tj861zhd.js} +1 -1
- package/dist/cli/{index-txh3h83v.js → index-vj9bba5k.js} +3 -3
- package/dist/cli/{index-fksfxhmx.js → index-vmfaafte.js} +5 -5
- package/dist/cli/{index-19f0zycs.js → index-y3hmyvt6.js} +2 -2
- package/dist/cli/{index-n7trn9wz.js → index-yxhcy5cm.js} +1 -1
- package/dist/cli/{index-4qvsh3m5.js → index-z5ppkn8y.js} +3 -3
- package/dist/cli/{index-h8qed3pr.js → index-z9ed68jt.js} +1 -1
- package/dist/cli/index.js +17 -17
- package/dist/cli/{knowledge-escalator-wj85ppdt.js → knowledge-escalator-mn4sx4qd.js} +6 -6
- package/dist/cli/{knowledge-events-4y9kk2xe.js → knowledge-events-x975ngy4.js} +4 -4
- package/dist/cli/{knowledge-store-kc8dwc14.js → knowledge-store-33p762ey.js} +1 -1
- package/dist/cli/{knowledge-validator-584ga9fb.js → knowledge-validator-q5jc0scs.js} +2 -2
- package/dist/cli/{scan-cursor-rhjym1pn.js → scan-cursor-p7t5mb4x.js} +2 -2
- package/dist/cli/{schema-yb3pvhcs.js → schema-t8bmshhj.js} +1 -1
- package/dist/cli/{scope-persistence-bxwjk9rc.js → scope-persistence-2kyrgsca.js} +4 -4
- package/dist/cli/{skill-generator-3w8w7htr.js → skill-generator-fwvmcv8m.js} +7 -7
- package/dist/cli/{worktree-isolation-av1rshr3.js → worktree-isolation-87j70zg1.js} +17 -17
- package/dist/hooks/knowledge-application-gate.d.ts +23 -0
- package/dist/index.js +17 -16
- 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.146.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.146.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -6460,9 +6460,10 @@ ${promptRaw}`,log("[delegate-directive-injection] injected",{caller_agent:caller
|
|
|
6460
6460
|
`,"utf-8")}catch(error93){throw error48(`[full-auto/delegation] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`),error93}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/delegation] lock release failed:",releaseError)}}}function createFullAutoDelegationHook(options){let{config:config3,directory}=options;return{toolBefore:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let args2=output.args??{},subagentRaw=typeof args2.subagent_type==="string"&&args2.subagent_type||typeof args2.agent==="string"&&args2.agent||"",generatedAgentRegistry=swarmState.generatedAgentNames,canonicalRole=generatedAgentRegistry.length>0?resolveGeneratedAgentRole(subagentRaw,generatedAgentRegistry):getCanonicalAgentRole(subagentRaw);if(subagentRaw&&canonicalRole!==subagentRaw&&!isExactCanonicalRole(subagentRaw)){if(!subagentRaw.slice(0,subagentRaw.length-canonicalRole.length-1))throw Error(`FULL_AUTO_DELEGATION_DENY: subagent name '${subagentRaw}' has no valid prefix before the canonical role '${canonicalRole}'. Generated agent names must include a non-empty swarm prefix.`)}let promptText=typeof args2.prompt==="string"&&args2.prompt||typeof args2.message==="string"&&args2.message||typeof args2.task==="string"&&args2.task||"";if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(promptText&&typeof promptText==="string"){let candidatePaths=promptText.match(/\b[A-Za-z0-9._/-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|toml|lock|sh|env)\b/g);if(candidatePaths){for(let p of candidatePaths)if(isProtectedPath(p,config3.full_auto))await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole,phase:"outbound",category:"protected_path_in_prompt",matched:p})}}},toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),warnings=detectReturnWarnings(text);if(warnings.length===0)return;let severe=warnings.some((w)=>SEVERE_CATEGORIES.has(w.category));if(await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,severe}),runState.counters.consecutiveNoProgressTurns=severe?runState.counters.consecutiveNoProgressTurns+1:runState.counters.consecutiveNoProgressTurns,saveFullAutoRunState(directory,runState),severe){let updated=loadFullAutoRunState(directory,sessionID);if(updated&&updated.status==="running")updated.status="paused",updated.pauseReason=`severe subagent return warning: ${warnings.filter((w)=>SEVERE_CATEGORIES.has(w.category)).map((w)=>w.category).join(",")}`,saveFullAutoRunState(directory,updated)}}}}import*as fs135 from"node:fs";var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key=`${category}:${m[0].toLowerCase()}`;if(seen.has(key))continue;seen.add(key),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_file_locks();init_logger();init_normalize_tool_name();init_utils2();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings},lockTaskId=`full-auto-input-warning-${Date.now()}`,lockResult;try{lockResult=await tryAcquireLock(directory,"events.jsonl","full-auto-input-warning",lockTaskId)}catch(error93){warn(`[full-auto/input-probe] failed to acquire lock: ${error93 instanceof Error?error93.message:String(error93)}`)}try{let eventsPath=validateSwarmPath(directory,"events.jsonl");fs135.appendFileSync(eventsPath,`${JSON.stringify(event)}
|
|
6461
6461
|
`,"utf-8")}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/input-probe] lock release failed:",releaseError)}}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate2=out;if(typeof candidate2.output==="string")return candidate2.output;if(typeof candidate2.text==="string")return candidate2.text;if(typeof candidate2.body==="string")return candidate2.body;try{return JSON.stringify(candidate2)}catch{return""}}return""}var MAX_TRACKED_SESSIONS9=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs-at>WARNING_TTL_MS}function evictExpired(){let now2=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now2))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS9){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_policy();init_state3();init_scope_persistence();init_state2();init_normalize_tool_name();function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let toolName=normalizeToolName(input.tool)??input.tool,sessionID=input.sessionID;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(isReadOnlyTool(toolName))return;let rawReason=runState.pauseReason??runState.terminateReason??"no reason recorded",statusPrefix=rawReason.includes("infrastructure failure")&&runState.status==="paused"?"FULL_AUTO_PAUSED:OVERSIGHT_INFRASTRUCTURE_FAILURE":`FULL_AUTO_${runState.status.toUpperCase()}`;throw Error(`${statusPrefix}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${rawReason}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,binding=taskId?resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionID});if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,toolName,args:argsObj,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session&&taskId?getModifiedFilesForTask(session,taskId):void 0,fullAutoConfig:effectiveFullAutoConfig},decision=classifyFullAutoToolAction(classifierInput),pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl))decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")})`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}if(decision.action==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1,max_dispatch_retries:fullAutoConfig?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:fullAutoConfig?.oversight?.max_consecutive_dispatch_failures??3}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_gate_denial_tracker();init_guardrails2();init_hive_promoter();init_stored_input_args();init_spawn_helper();import*as fs136 from"node:fs";import*as path240 from"node:path";var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs136.existsSync(path240.join(projectDir,"bun.lockb")))return"bun";if(fs136.existsSync(path240.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs136.existsSync(path240.join(projectDir,"yarn.lock")))return"yarn";if(fs136.existsSync(path240.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path240.join(projectDir,"package.json");if(fs136.existsSync(pkgPath))try{let pkg=JSON.parse(fs136.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs136.existsSync(path240.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs136.existsSync(path240.join(projectDir,"tsconfig.json")))return{command:["npx","tsc","--noEmit"],language:"typescript"}}catch{return null}if(fs136.existsSync(path240.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs136.existsSync(path240.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs136.existsSync(path240.join(projectDir,"pyproject.toml"))||fs136.existsSync(path240.join(projectDir,"requirements.txt"))||fs136.existsSync(path240.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs136.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(input.tool!=="Task")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
|
|
6462
6462
|
${errorSummary}`)}}}}init_delegation_health();init_pending_delegations();init_constants();init_file_locks();init_state2();init_recovery();init_utils();init_core3();init_merge();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();import*as fs137 from"node:fs";import*as fsPromises10 from"node:fs/promises";import*as path241 from"node:path";var INIT_ORPHAN_RECOVERY_TIMEOUT_MS=1e4,OWNERSHIP_TAG_SCAN_TIMEOUT_MS2=2000;async function listOwnershipTagSessionIds(directory){let scan=await scanBackgroundWorktreeOwnershipTagsForRecovery(directory);if(scan.status==="uncertain")return scan;return{status:"ok",sessionIds:[...new Set(scan.owners.map((owner)=>owner.sessionId))]}}var ORPHAN_RECOVERY_LOCK_FILE=WORKTREE_LIFECYCLE_LOCK_FILE,_internals182={rmSync:fs137.rmSync,removeWorktree,isLocked,listActiveLocks,tryAcquireLock,listOwnershipTagSessionIds,scanDelegationsForRecovery,recordDelegationRecoveryObservation,scanDelegationFallbacksForRecovery,scanWorktreeMergeFailuresForRecovery,scanWorktreeProvisioningOwnersForRecovery,scanRegisteredWorktreeLiveness,removeWorktreeProvisioningOwner};async function writeAdvisoryFile(directory,cleanupResult,warnings,attempted,removedWorktrees=[]){let advisoryPath=path241.join(directory,".swarm","advisories","init-orphan-recovery.json"),advisory={initTimestamp:new Date().toISOString(),warnings,errors:cleanupResult.errors,reclaimed:{removedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:attempted},...cleanupResult.skippedRecoveryBranches&&cleanupResult.skippedRecoveryBranches.length>0?{preservedRecoveryBranches:cleanupResult.skippedRecoveryBranches}:{},...cleanupResult.recoveryReadError?{recoveryReadError:!0,note:"skipped all lane-branch deletions this pass because .swarm/recovery/ was unreadable (fail-safe)"}:{}};try{await fsPromises10.mkdir(path241.dirname(advisoryPath),{recursive:!0}),await fsPromises10.writeFile(advisoryPath,JSON.stringify(advisory,null,2),"utf-8")}catch{log("initOrphanRecovery advisory file write failed (non-fatal)")}}async function enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths=new Set){let orphanedDirs=[],worktreeRoot=path241.resolve(path241.dirname(directory),SWARM_WORKTREE_DIR_NAME),entries;try{entries=await fsPromises10.readdir(worktreeRoot,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let sessionId=entry.name;if(activeSessionIds.includes(sessionId))continue;let sessionEntries;try{sessionEntries=await fsPromises10.readdir(path241.join(worktreeRoot,sessionId),{withFileTypes:!0})}catch{continue}for(let laneEntry of sessionEntries){if(!laneEntry.isDirectory())continue;let worktreePath=path241.join(worktreeRoot,sessionId,laneEntry.name);if(protectedWorktreePaths.has(path241.resolve(worktreePath)))continue;orphanedDirs.push(worktreePath)}}return orphanedDirs}async function isCrossProcessLockHeld(directory){if(_internals182.isLocked(directory,ORPHAN_RECOVERY_LOCK_FILE))return!0;if(_internals182.listActiveLocks(directory).length>0)return!0;return!1}async function removeOrphanedWorktreeDir(worktreePath,projectRoot){if(!fs137.existsSync(path241.join(worktreePath,".git")))try{_internals182.rmSync(worktreePath,{recursive:!0,force:!0});return}catch(error93){return error93 instanceof Error?error93.message:String(error93)}let removeResult=await _internals182.removeWorktree(worktreePath,projectRoot);if(!("error"in removeResult))return;try{_internals182.rmSync(worktreePath,{recursive:!0,force:!0});return}catch{return removeResult.error}}async function crossProcessAdvisoryResult(directory,warning){let result={attempted:!0,crossProcessLockHeld:!0,warnings:[warning],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1};return await writeAdvisoryFile(directory,{removed:[],skipped:[],errors:[]},result.warnings,!1,[]),result}function worktreePathKey(worktreePath,directory){let absolutePath2=path241.isAbsolute(worktreePath)?worktreePath:path241.resolve(directory,worktreePath),normalized=path241.normalize(absolutePath2);return process.platform==="win32"?normalized.toLowerCase():normalized}async function runInitOrphanRecovery(directory){let result,recoveryLockRelease;try{if(await isCrossProcessLockHeld(directory))return crossProcessAdvisoryResult(directory,"Cross-process lock held — another opencode process may be active. "+"Skipping destructive cleanup to preserve its worktrees/branches. Run '/swarm status' or check '.swarm/locks/' to identify active processes.");let lockAcquireResult=await _internals182.tryAcquireLock(directory,ORPHAN_RECOVERY_LOCK_FILE,"init-orphan-recovery","init");if(!lockAcquireResult.acquired)return crossProcessAdvisoryResult(directory,"Cross-process lifecycle lock was acquired by another process during init; skipping destructive cleanup to preserve its worktrees/branches.");recoveryLockRelease=lockAcquireResult.lock._release;let activeSessionIds=Array.from(swarmState.agentSessions.keys()),provisioningOwnerScan=await withTimeout(Promise.resolve(_internals182.scanWorktreeProvisioningOwnersForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree provisioning ownership scan exceeded its bounded init budget"));if(provisioningOwnerScan.status==="uncertain")throw Error(`worktree provisioning ownership state is uncertain; destructive orphan cleanup skipped: ${provisioningOwnerScan.reason}`);let registeredWorktrees=provisioningOwnerScan.owners.length===0?{status:"ok",liveBranches:[]}:await withTimeout(_internals182.scanRegisteredWorktreeLiveness(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("registered worktree liveness scan exceeded its bounded init budget"));if(registeredWorktrees.status==="uncertain")throw Error(`registered worktree liveness is uncertain; destructive orphan cleanup skipped: ${registeredWorktrees.reason}`);let liveBranches=new Set(registeredWorktrees.liveBranches),now2=Date.now();for(let owner of provisioningOwnerScan.owners){let leaseIsLive=now2-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS,sessionIds=new Set([owner.parentSessionId,owner.worktreeSessionId]),branchIsLive=owner.schemaVersion===2?[...sessionIds].some((sessionId)=>liveBranches.has(`swarm/lane/${sessionId}/${owner.taskId}`)||liveBranches.has(`swarm-lane/${sessionId}/${owner.taskId}`)):[...liveBranches].some((branch)=>{let segments=branch.split("/"),sessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;return sessionId!==void 0&&sessionIds.has(sessionId)});if(!leaseIsLive&&!branchIsLive){if(!_internals182.removeWorktreeProvisioningOwner(directory,owner.callID))throw Error(`expired worktree provisioning owner ${owner.callID} could not be removed; destructive orphan cleanup skipped`);continue}if(!activeSessionIds.includes(owner.worktreeSessionId))activeSessionIds.push(owner.worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}let ownershipTagScan=await withTimeout(_internals182.listOwnershipTagSessionIds(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("background ownership tag scan exceeded its bounded init budget"));if(ownershipTagScan.status==="uncertain")throw Error(`background ownership tag state is uncertain; destructive orphan cleanup skipped: ${ownershipTagScan.reason}`);for(let sessionId of ownershipTagScan.sessionIds)if(!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);let fallbackOwnerScan=await withTimeout(_internals182.scanDelegationFallbacksForRecovery(directory),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background delegation fallback ownership scan exceeded its bounded init budget"));if(fallbackOwnerScan.status==="uncertain")throw Error(`background fallback ownership state is uncertain; destructive orphan cleanup skipped: ${fallbackOwnerScan.reason}`);let primaryOwnerScan=await withTimeout(Promise.resolve(_internals182.scanDelegationsForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background primary ownership scan exceeded its bounded init budget"));if(primaryOwnerScan.status==="uncertain")throw _internals182.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!1,reason:primaryOwnerScan.reason,...primaryOwnerScan.repairHint?{repairHint:primaryOwnerScan.repairHint}:{}}),Error(`background primary ownership state is uncertain; destructive orphan cleanup skipped: ${primaryOwnerScan.reason}`);_internals182.recordDelegationRecoveryObservation(directory,{source:primaryOwnerScan.source??"legacy-ledger",ok:!0});let isUnsettledOwner=(record3)=>isUnsettledWorktreeOwner(record3),durableWorktreeOwners=primaryOwnerScan.owners.filter(isUnsettledOwner),mergeOwnerScan=await withTimeout(Promise.resolve(_internals182.scanWorktreeMergeFailuresForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree merge ownership scan exceeded its bounded init budget"));if(mergeOwnerScan.status==="uncertain")throw Error(`worktree merge ownership state is uncertain; destructive orphan cleanup skipped: ${mergeOwnerScan.reason}`);let allDurableOwners=[...durableWorktreeOwners,...fallbackOwnerScan.owners.map((artifact)=>artifact.record).filter(isUnsettledOwner)],preservedMergeFailures=mergeOwnerScan.failures.map(([,failure])=>failure).filter((failure)=>typeof failure.worktreePath==="string"),protectedWorktreePaths=new Set([...allDurableOwners.map((record3)=>record3.worktree?.worktreePath),...preservedMergeFailures.map((failure)=>failure.worktreePath)].filter((value)=>typeof value==="string").map((value)=>path241.resolve(value)));for(let owner of allDurableOwners){let worktreeSessionId=owner.worktree?.worktreeSessionId;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}for(let failure of preservedMergeFailures){let segments=failure.branch?.split("/")??[],worktreeSessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId)}let orphanedWorktreeDirs=await withTimeout(enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during worktree enumeration; continuing without orphan reclamation`)),removedWorktrees=[],worktreeWarnings=[],recoveryRecords=listRecoveryRecords(directory),recoveryReadError=recoveryReadErrored(directory),recoveryWorktreePaths=new Set(recoveryRecords.map((record3)=>worktreePathKey(record3.worktreePath,directory)));if(recoveryReadError)worktreeWarnings.push("Recovery records are unreadable or fail schema validation; skipped all orphaned worktree deletion this pass (fail-safe).");else for(let worktreePath of orphanedWorktreeDirs){if(recoveryWorktreePaths.has(worktreePathKey(worktreePath,directory))){worktreeWarnings.push(`Preserved recovery worktree "${worktreePath}"; an unresolved recovery record still references it.`);continue}let error93=await removeOrphanedWorktreeDir(worktreePath,directory);if(error93)worktreeWarnings.push(`Could not reclaim orphaned worktree "${worktreePath}": ${error93}`);else removedWorktrees.push(worktreePath)}let cleanupResult=await withTimeout(cleanupOrphanedBranches(directory,activeSessionIds,{preserveUnmerged:!0}),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during branch cleanup; continuing without orphan reclamation`)),branchWarnings=cleanupResult.errors.map((e)=>`Could not delete orphaned branch "${e.branch}": ${e.error}`),allWarnings=[...worktreeWarnings,...branchWarnings];result={attempted:!0,crossProcessLockHeld:!1,warnings:allWarnings,orphanedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:cleanupResult.recoveryReadError!==!0},await writeAdvisoryFile(directory,cleanupResult,allWarnings,!0,removedWorktrees)}catch(err){let msg=err instanceof Error?err.message:String(err);log("initOrphanRecovery timed out or failed (non-fatal)",{error:msg}),result={attempted:!1,crossProcessLockHeld:!1,warnings:[`Orphan recovery timed out or failed: ${msg}`],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1,diagnostic:{file:".swarm/advisories/init-orphan-recovery.json",reason:msg}},await writeAdvisoryFile(directory,{removed:[],skipped:[],skippedRecoveryBranches:[],errors:[]},result.warnings,!1,[])}finally{try{await recoveryLockRelease?.()}catch{}}return result}init_state2();import*as fs138 from"node:fs/promises";import*as path242 from"node:path";var ADVISORY_FILENAME="init-orphan-recovery.json";function createInitOrphanRecoveryAdvisoryHook(directory){let consumedBySession=new Set;async function readAdvisoryFile(){let advisoryPath=path242.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{let content=await fs138.readFile(advisoryPath,"utf-8");return JSON.parse(content)}catch{return null}}async function deleteAdvisoryFile(){let advisoryPath=path242.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{await fs138.unlink(advisoryPath)}catch{}}function formatError3(error93){return`ORPHAN_RECOVERY_ERROR: Could not reclaim branch "${error93.branch}": ${error93.error}`}async function messagesTransform(_input,output){let messages=output.messages;if(!messages||messages.length===0)return;let sessionId=messages[messages.length-1]?.info?.sessionID;if(!sessionId)return;let activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),ORCHESTRATOR_NAME2="Architect";if(!(activeAgent?activeAgent===ORCHESTRATOR_NAME2||activeAgent.endsWith("_Architect"):session?session.agentName===ORCHESTRATOR_NAME2||session.agentName.endsWith("_Architect"):!1))return;if(consumedBySession.has(sessionId))return;let advisory=await readAdvisoryFile();if(!advisory)return;consumedBySession.add(sessionId),await deleteAdvisoryFile();let reclaimedForGate=advisory.reclaimed;if(!((advisory.warnings?.length??0)>0||(advisory.errors?.length??0)>0||(reclaimedForGate?.removedBranches?.length??0)>0||(reclaimedForGate?.removedWorktrees?.length??0)>0))return;let targetSession=ensureAgentSession(sessionId),timestamp=advisory.initTimestamp?new Date(advisory.initTimestamp).toLocaleString():"unknown";pushAdvisory(targetSession,`[INIT ORPHAN RECOVERY] Plugin init detected the following at ${timestamp}:`);for(let warning of advisory.warnings??[])pushAdvisory(targetSession,` WARNING: ${warning}`);for(let err of advisory.errors??[])pushAdvisory(targetSession,` ERROR: ${formatError3(err)}`);let reclaimed=advisory.reclaimed;if((reclaimed?.removedBranches?.length??0)>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedBranches.length} orphaned branch(es): ${reclaimed.removedBranches.join(", ")}`);if(reclaimed?.removedWorktrees&&reclaimed.removedWorktrees.length>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedWorktrees.length} orphaned worktree directory(ies): ${reclaimed.removedWorktrees.join(", ")}`);if(reclaimed?.prunedWorktrees)pushAdvisory(targetSession," Stale worktree metadata pruned.")}return{messagesTransform}}init_logger();init_delegation_gate();import*as fs139 from"node:fs";import*as path244 from"node:path";function computeNextMode(params){let{issueReference,traceState,workflowArtifacts}=params,noop={nextMode:null,directive:null,nextLastTransition:traceState.lastTransition,nextStatus:traceState.status};if(!issueReference||issueReference.flags.trace!==!0)return noop;if(traceState.status==="published")return noop;if(traceState.status==="publication_handoff"){if(workflowArtifacts.publicationObserved&&traceState.lastTransition!=="PUBLISHED")return{nextMode:null,directive:"Publication confirmed. The issue-trace workflow is complete.",nextLastTransition:"PUBLISHED",nextStatus:"published"};return noop}if(workflowArtifacts.specIssueNumber===null||workflowArtifacts.specIssueNumber!==issueReference.number||traceState.issueNumber!==issueReference.number)return noop;if(!workflowArtifacts.specExists)return noop;if(!workflowArtifacts.planExists){if(!workflowArtifacts.reproductionPermitted){if(traceState.lastTransition===null)return{nextMode:"ISSUE_INGEST",directive:"Reproduction evidence (or a typed --no-repro waiver) is required before this trace can transition to PLAN. Attempt a minimal reproduction and call record_issue_reproduction (performed: true, commands, output_summary), or restart with /swarm issue --no-repro.",nextLastTransition:"REPRO_GATE",nextStatus:"in_progress"};return noop}if(traceState.lastTransition===null||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN"||traceState.lastTransition==="REPRO_GATE"){if(traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return noop;return{nextMode:"PLAN",directive:null,nextLastTransition:"ISSUE_INGEST_TO_PLAN",nextStatus:"in_progress"}}return noop}if(!workflowArtifacts.criticApproved)return noop;if(workflowArtifacts.planExists&&!workflowArtifacts.allPhasesComplete){if(traceState.lastTransition==="PLAN_TO_EXECUTE")return noop;return{nextMode:"EXECUTE",directive:null,nextLastTransition:"PLAN_TO_EXECUTE",nextStatus:"in_progress"}}if(!workflowArtifacts.planExists)return noop;if(!workflowArtifacts.implementationReviewVerified&&traceState.lastTransition!=="REVIEW_GATE"&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"All implementation phases are complete, but the independent implementation review is not yet recorded. Dispatch a FRESH-context reviewer and then a FRESH-context critic over the implementation diff (separate contexts from the implementer); when both approve, call record_implementation_review (issueNumber, reviewerVerdict APPROVE, criticVerdict APPROVE, the reviewed diff base/head, and notes). The trace will not hand off to commit-pr until this receipt exists.",nextLastTransition:"REVIEW_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&!workflowArtifacts.recurrenceSweepVerified&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:'The implementation review is approved, but the recurrence sweep is not yet recorded. Characterize the defect class, search the repository with explicit predicates, disposition every hit (FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and install a guardrail that provably catches the original defect — or record the "no defect class" fast path with a one-line justification. Then call record_recurrence_sweep. The trace will not hand off to commit-pr until this receipt exists.',nextLastTransition:"RECURRENCE_GATE",nextStatus:"in_progress"};if(!workflowArtifacts.implementationReviewVerified||!workflowArtifacts.recurrenceSweepVerified)return noop;if(traceState.lastTransition==="EXECUTE_TO_COMMIT")return noop;return{nextMode:null,directive:"All implementation phases are complete. Compose commit-pr to publish the PR. Read .swarm/issue-reference.json for Closes #N. After the PR is created/updated, call record_issue_publication (with the issue number, PR number, URL, and HEAD sha) so this trace reaches its terminal published state — the trace is NOT complete until publication is confirmed.",nextLastTransition:"EXECUTE_TO_COMMIT",nextStatus:"publication_handoff"}}init_manager();import{existsSync as existsSync127,mkdirSync as mkdirSync65,readFileSync as readFileSync95,renameSync as renameSync34,unlinkSync as unlinkSync34,writeFileSync as writeFileSync41}from"node:fs";import*as path243 from"node:path";async function _defaultLoadPlanFromLedger(directory){return loadPlan(directory)}async function _defaultReproductionReceiptExists(directory,issueNumber){try{let filePath=path243.join(directory,".swarm","reproduction.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.performed===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultPublicationReceiptExists(directory,issueNumber){try{let filePath=path243.join(directory,".swarm","issue-publication.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.published===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultRecurrenceSweepReceiptExists(directory,issueNumber){try{let filePath=path243.join(directory,".swarm","recurrence-sweep.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber||typeof o.defectClass!=="string"||o.defectClass.trim().length===0)return!1;if(o.defectClass!=="no defect class"){let{predicates,dispositions,guardrail}=o,validPredicates=Array.isArray(predicates)&&predicates.length>0&&predicates.every((p)=>typeof p==="string"&&p.trim().length>0),validDispositions=Array.isArray(dispositions)&&dispositions.every((d)=>typeof d==="object"&&d!==null&&typeof d.ref==="string"&&["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"].includes(String(d.disposition))),validGuardrail=typeof guardrail==="object"&&guardrail!==null&&typeof guardrail.kind==="string"&&typeof guardrail.proof==="string";if(!validPredicates||!validDispositions||!validGuardrail)return!1}else if(typeof o.justification!=="string"||o.justification.trim().length===0)return!1;return!0}catch{return!1}}async function _defaultImplementationReviewReceiptExists(directory,issueNumber){try{let filePath=path243.join(directory,".swarm","implementation-review.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.issueNumber===issueNumber&&o.reviewerVerdict==="APPROVE"&&o.criticVerdict==="APPROVE"}catch{return!1}}var _internals183={readFileSync:readFileSync95,writeFileSync:writeFileSync41,existsSync:existsSync127,renameSync:renameSync34,mkdirSync:mkdirSync65,unlinkSync:unlinkSync34,loadPlanFromLedger:_defaultLoadPlanFromLedger,reproductionReceiptExists:_defaultReproductionReceiptExists,publicationReceiptExists:_defaultPublicationReceiptExists,recurrenceSweepReceiptExists:_defaultRecurrenceSweepReceiptExists,implementationReviewReceiptExists:_defaultImplementationReviewReceiptExists},TRACE_STATUSES=["in_progress","publication_handoff","published"];function isTraceStatus(value){return typeof value==="string"&&TRACE_STATUSES.includes(value)}function isPhaseComplete(status){return status==="complete"||status==="completed"}function isValidIssueReference(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;if(typeof o.url!=="string"||!o.url.startsWith("https://github.com/"))return!1;return typeof o.owner==="string"&&typeof o.repo==="string"&&typeof o.number==="number"&&typeof o.timestamp==="string"&&typeof o.flags==="object"&&o.flags!==null}function isValidTraceStateShape(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.issueNumber==="number"&&(o.lastTransition===null||typeof o.lastTransition==="string")}function normalizeTraceState(obj){let status;if(isTraceStatus(obj.status))status=obj.status;else if(obj.status===void 0&&typeof obj.completed==="boolean")status=obj.completed?"publication_handoff":"in_progress";else status="in_progress";return{issueNumber:obj.issueNumber,lastTransition:obj.lastTransition===null||typeof obj.lastTransition==="string"?obj.lastTransition:null,status}}function readIssueReference(directory){try{let filePath=path243.join(directory,".swarm","issue-reference.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidIssueReference(parsed))return null;return parsed}catch{return null}}function readTraceState(directory){let defaultState={issueNumber:0,lastTransition:null,status:"in_progress"};try{let filePath=path243.join(directory,".swarm","issue-trace-state.json"),raw=_internals183.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidTraceStateShape(parsed))return defaultState;return normalizeTraceState(parsed)}catch{return defaultState}}function writeTraceState(directory,state){let swarmDir=path243.join(directory,".swarm");_internals183.mkdirSync(swarmDir,{recursive:!0});let finalPath=path243.join(swarmDir,"issue-trace-state.json"),tmpPath=path243.join(swarmDir,`issue-trace-state.tmp.${process.pid}.${Date.now()}.json`);_internals183.writeFileSync(tmpPath,JSON.stringify(state,null,2),"utf-8");try{_internals183.renameSync(tmpPath,finalPath)}catch{try{_internals183.unlinkSync(finalPath)}catch{}try{_internals183.renameSync(tmpPath,finalPath)}catch(retryErr){try{_internals183.unlinkSync(tmpPath)}catch{}throw retryErr}}}function readSpecIssueNumber(directory){try{let filePath=path243.join(directory,".swarm","spec.md"),raw=_internals183.readFileSync(filePath,"utf-8"),sectionStart=raw.indexOf("## Source Issue");if(sectionStart===-1)return null;let nextHeading=raw.indexOf(`
|
|
6463
|
-
## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals183.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{planExists:!1,allComplete:!1};return{planExists:!0,allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status))}}function specExists(directory){return _internals183.existsSync(path243.join(directory,".swarm","spec.md"))}async function reproductionReceiptExists(directory,issueNumber){return _internals183.reproductionReceiptExists(directory,issueNumber)}async function publicationReceiptExists(directory,issueNumber){return _internals183.publicationReceiptExists(directory,issueNumber)}async function recurrenceSweepReceiptExists(directory,issueNumber){return _internals183.recurrenceSweepReceiptExists(directory,issueNumber)}async function implementationReviewReceiptExists(directory,issueNumber){return _internals183.implementationReviewReceiptExists(directory,issueNumber)}var _internals184={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,reproductionReceiptExists,publicationReceiptExists,recurrenceSweepReceiptExists,implementationReviewReceiptExists,isPlanCriticApproved,logError:error48},cachedApproval=null,cachedPhaseStatus=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath2=path244.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1;try{currentSize=fs139.statSync(ledgerPath2).size}catch{let timeout=new Promise((resolve98)=>{setTimeout(()=>resolve98(!1),timeoutMs)});return await Promise.race([_internals184.isPlanCriticApproved(directory),timeout])}if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.size===currentSize)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve98)=>{timer=setTimeout(()=>resolve98(!1),timeoutMs)}),result=await Promise.race([_internals184.isPlanCriticApproved(directory),timeout]);return cachedApproval={dir:directory,size:currentSize,result},result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}async function cachedReadPlanPhaseStatus(directory){let planJsonPath=path244.join(directory,".swarm","plan.json"),currentSize=-1,currentMtime=-1;try{let stat21=fs139.statSync(planJsonPath);currentSize=stat21.size,currentMtime=stat21.mtimeMs}catch{}if(cachedPhaseStatus&&cachedPhaseStatus.dir===directory&&cachedPhaseStatus.planJsonSize===currentSize&&cachedPhaseStatus.planJsonMtime===currentMtime)return cachedPhaseStatus.result;let result=await _internals184.readPlanPhaseStatus(directory);return cachedPhaseStatus={dir:directory,planJsonSize:currentSize,planJsonMtime:currentMtime,result},result}function createIssueTraceHook(_config,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals184.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals184.readTraceState(directory),_specExists=_internals184.specExists(directory),_specIssueNumber=_internals184.readSpecIssueNumber(directory),phaseStatus=await cachedReadPlanPhaseStatus(directory),_criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_reproReceipt=await _internals184.reproductionReceiptExists(directory,issueRef.number),_reproductionPermitted=issueRef.flags.noRepro===!0||issueRef.noReproWaiver?.waived===!0||_reproReceipt,_publicationObserved=await _internals184.publicationReceiptExists(directory,issueRef.number),_implementationReviewVerified=await _internals184.implementationReviewReceiptExists(directory,issueRef.number),_recurrenceSweepVerified=await _internals184.recurrenceSweepReceiptExists(directory,issueRef.number),result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:phaseStatus.planExists,criticApproved:_criticApproved,allPhasesComplete:phaseStatus.allComplete,reproductionPermitted:_reproductionPermitted,publicationObserved:_publicationObserved,implementationReviewVerified:_implementationReviewVerified,recurrenceSweepVerified:_recurrenceSweepVerified}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,messagesToAdd=[];if(result.nextMode!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:`[MODE: ${result.nextMode}]`}]});if(finalDirective!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:finalDirective}]});let out=output;if(!Array.isArray(out.messages)||messagesToAdd.length===0)return;out.messages.push(...messagesToAdd),_internals184.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,status:result.nextStatus})}catch(err){_internals184.logError("[issue-trace] hook cycle failed:",err)}}}}init_schema();init_state2();init_logger();import{appendFile as appendFile26,mkdir as mkdir52}from"node:fs/promises";import*as path245 from"node:path";init_knowledge_receipt_ledger();var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;function selectCurrentArchitectDirectiveMemberships(memberships){let activeArchitect=memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.phase_closed_at),latest,latestAt=Number.NEGATIVE_INFINITY;for(let membership of activeArchitect){let committedAt=Date.parse(membership.committed_at),comparableAt=Number.isFinite(committedAt)?committedAt:Number.NEGATIVE_INFINITY;if(!latest||comparableAt>=latestAt)latest=membership,latestAt=comparableAt}if(!latest)return[];return activeArchitect.filter((membership)=>membership.phase===latest.phase&&membership.task_id===latest.task_id)}function selectStaleUnmarkedMemberships(memberships,now2,stalenessMs){return memberships.filter((membership)=>{if(membership.application_marker||hasEffectiveGateRelease(membership))return!1;let committedAt=Date.parse(membership.committed_at);return Number.isFinite(committedAt)&&now2-committedAt>stalenessMs})}function hasEffectiveGateRelease(membership){return membership.gate_release?.membership_event_id===membership.membership_event_id}function groupMembershipsByTrace(memberships){let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}return byTrace}async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");_internals185.writeWarnEvent(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let receiptState=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!receiptState.ok){if(config3.mode==="enforce")throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: receipt authority unavailable (${receiptState.code}); refusing to infer acknowledgment from diagnostics`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,reason:receiptState.code});return}let criticalMemberships=selectCurrentArchitectDirectiveMemberships(receiptState.memberships).filter((membership)=>membership.critical);if(criticalMemberships.length===0){clearGateDenialCount(sessionID);return}let unackedMemberships=criticalMemberships.filter((membership)=>!membership.application_marker&&!hasEffectiveGateRelease(membership));if(unackedMemberships.length===0){clearGateDenialCount(sessionID);return}if(config3.mode==="enforce"&&config3.critical_requires_ack){let maxDenials=config3.max_gate_denials??DEFAULT_MAX_GATE_DENIALS,stalenessMs=config3.gate_staleness_ms??DEFAULT_GATE_STALENESS_MS,now2=Date.now(),staleMemberships=selectStaleUnmarkedMemberships(unackedMemberships,now2,stalenessMs);if(staleMemberships.length>0){for(let[traceId,memberships]of groupMembershipsByTrace(staleMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_staleness_release",reason:"configured staleness escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record staleness release")}let stalePairs=new Set(staleMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`));unackedMemberships=unackedMemberships.filter((membership)=>!stalePairs.has(`${membership.trace_id}/${membership.entry_id}`));let staleIds=[...new Set(staleMemberships.map((membership)=>membership.entry_id))];if(clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_staleness_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:staleIds,cleared_pairs:[...stalePairs],age_ms:Math.max(...staleMemberships.map((membership)=>now2-Date.parse(membership.committed_at))),staleness_threshold_ms:stalenessMs}).catch((err)=>{warn(`[knowledge-application-gate] staleness-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)}),unackedMemberships.length===0){clearCriticalShownIds(sessionID);return}}let unackedPairs2=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`),unacked2=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],directiveKey=buildGateDenialDirectiveKey(unackedPairs2),denials=incrementGateDenialCount(sessionID,directiveKey);if(denials>maxDenials){for(let[traceId,memberships]of groupMembershipsByTrace(unackedMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_denial_limit_release",reason:"configured denial-count escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record denial-limit release")}clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_denial_limit_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked2,denial_count:denials,max_gate_denials:maxDenials}).catch((err)=>{warn(`[knowledge-application-gate] denial-limit-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let ids=unackedPairs2.join(", ");throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — critical knowledge membership(s) ${ids} require exact-pair KNOWLEDGE_APPLIED:<trace_id>:<entry_id>, KNOWLEDGE_N_A:<trace_id>:<entry_id> reason=... (does not apply; neutral), KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=... (relevant but deliberately not followed), KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=..., or KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=... before this action.`)}let unacked=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],unackedPairs=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked,unacknowledged_critical_pairs:unackedPairs}).catch(()=>{})}async function writeWarnEvent2(directory,record3){let filePath=path245.join(directory,".swarm","events.jsonl");await mkdir52(path245.dirname(filePath),{recursive:!0}),await appendFile26(filePath,`${JSON.stringify(record3)}
|
|
6463
|
+
## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals183.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{planExists:!1,allComplete:!1};return{planExists:!0,allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status))}}function specExists(directory){return _internals183.existsSync(path243.join(directory,".swarm","spec.md"))}async function reproductionReceiptExists(directory,issueNumber){return _internals183.reproductionReceiptExists(directory,issueNumber)}async function publicationReceiptExists(directory,issueNumber){return _internals183.publicationReceiptExists(directory,issueNumber)}async function recurrenceSweepReceiptExists(directory,issueNumber){return _internals183.recurrenceSweepReceiptExists(directory,issueNumber)}async function implementationReviewReceiptExists(directory,issueNumber){return _internals183.implementationReviewReceiptExists(directory,issueNumber)}var _internals184={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,reproductionReceiptExists,publicationReceiptExists,recurrenceSweepReceiptExists,implementationReviewReceiptExists,isPlanCriticApproved,logError:error48},cachedApproval=null,cachedPhaseStatus=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath2=path244.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1;try{currentSize=fs139.statSync(ledgerPath2).size}catch{let timeout=new Promise((resolve98)=>{setTimeout(()=>resolve98(!1),timeoutMs)});return await Promise.race([_internals184.isPlanCriticApproved(directory),timeout])}if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.size===currentSize)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve98)=>{timer=setTimeout(()=>resolve98(!1),timeoutMs)}),result=await Promise.race([_internals184.isPlanCriticApproved(directory),timeout]);return cachedApproval={dir:directory,size:currentSize,result},result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}async function cachedReadPlanPhaseStatus(directory){let planJsonPath=path244.join(directory,".swarm","plan.json"),currentSize=-1,currentMtime=-1;try{let stat21=fs139.statSync(planJsonPath);currentSize=stat21.size,currentMtime=stat21.mtimeMs}catch{}if(cachedPhaseStatus&&cachedPhaseStatus.dir===directory&&cachedPhaseStatus.planJsonSize===currentSize&&cachedPhaseStatus.planJsonMtime===currentMtime)return cachedPhaseStatus.result;let result=await _internals184.readPlanPhaseStatus(directory);return cachedPhaseStatus={dir:directory,planJsonSize:currentSize,planJsonMtime:currentMtime,result},result}function createIssueTraceHook(_config,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals184.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals184.readTraceState(directory),_specExists=_internals184.specExists(directory),_specIssueNumber=_internals184.readSpecIssueNumber(directory),phaseStatus=await cachedReadPlanPhaseStatus(directory),_criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_reproReceipt=await _internals184.reproductionReceiptExists(directory,issueRef.number),_reproductionPermitted=issueRef.flags.noRepro===!0||issueRef.noReproWaiver?.waived===!0||_reproReceipt,_publicationObserved=await _internals184.publicationReceiptExists(directory,issueRef.number),_implementationReviewVerified=await _internals184.implementationReviewReceiptExists(directory,issueRef.number),_recurrenceSweepVerified=await _internals184.recurrenceSweepReceiptExists(directory,issueRef.number),result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:phaseStatus.planExists,criticApproved:_criticApproved,allPhasesComplete:phaseStatus.allComplete,reproductionPermitted:_reproductionPermitted,publicationObserved:_publicationObserved,implementationReviewVerified:_implementationReviewVerified,recurrenceSweepVerified:_recurrenceSweepVerified}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,messagesToAdd=[];if(result.nextMode!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:`[MODE: ${result.nextMode}]`}]});if(finalDirective!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:finalDirective}]});let out=output;if(!Array.isArray(out.messages)||messagesToAdd.length===0)return;out.messages.push(...messagesToAdd),_internals184.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,status:result.nextStatus})}catch(err){_internals184.logError("[issue-trace] hook cycle failed:",err)}}}}init_schema();init_state2();init_logger();import{existsSync as existsSync128}from"node:fs";import{appendFile as appendFile26,mkdir as mkdir52}from"node:fs/promises";import*as path245 from"node:path";init_knowledge_receipt_ledger();init_knowledge_store();var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;function selectCurrentArchitectDirectiveMemberships(memberships){let activeArchitect=memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.phase_closed_at),latest,latestAt=Number.NEGATIVE_INFINITY;for(let membership of activeArchitect){let committedAt=Date.parse(membership.committed_at),comparableAt=Number.isFinite(committedAt)?committedAt:Number.NEGATIVE_INFINITY;if(!latest||comparableAt>=latestAt)latest=membership,latestAt=comparableAt}if(!latest)return[];return activeArchitect.filter((membership)=>membership.phase===latest.phase&&membership.task_id===latest.task_id)}function selectStaleUnmarkedMemberships(memberships,now2,stalenessMs){return memberships.filter((membership)=>{if(membership.application_marker||hasEffectiveGateRelease(membership))return!1;let committedAt=Date.parse(membership.committed_at);return Number.isFinite(committedAt)&&now2-committedAt>stalenessMs})}function hasEffectiveGateRelease(membership){return membership.gate_release?.membership_event_id===membership.membership_event_id}function groupMembershipsByTrace(memberships){let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}return byTrace}async function loadDirectiveContents(directory,entryIds){let contents=new Map;if(entryIds.length===0)return contents;let want=new Set(entryIds),sources=[resolveSwarmKnowledgePath(directory)];try{let hivePath=resolveHiveKnowledgePath2();if(existsSync128(hivePath))sources.push(hivePath)}catch{}for(let filePath of sources)try{let entries=await readKnowledge(filePath);for(let entry of entries)if(want.has(entry.id)&&!contents.has(entry.id)&&typeof entry.lesson==="string")contents.set(entry.id,entry.lesson)}catch{}return contents}function buildGateDenialMessage(toolName,memberships,contents){let pairs=memberships.map((m)=>`${m.trace_id}:${m.entry_id}`),examples=memberships.map((m)=>` KNOWLEDGE_N_A:${m.trace_id}:${m.entry_id} reason=<reason>`),contentLines=memberships.map((m)=>{let lesson=contents.get(m.entry_id);return` [${m.trace_id}:${m.entry_id}] ${lesson??"content not found in knowledge store — see the most recent <swarm_knowledge_directives> block or run knowledge_recall"}`});return[`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — unacknowledged critical knowledge directive(s): ${pairs.join(", ")}.`,"","Acknowledge each directive using its exact, colon-separated tokens (<trace_id>:<entry_id>) with one of these verb markers:"," KNOWLEDGE_APPLIED:<trace_id>:<entry_id>"," KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=<observable conflict>"," KNOWLEDGE_N_A:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=<short reason>","KNOWLEDGE_N_A (does not apply; neutral) is a valid, penalty-free acknowledgment when the directive does not pertain to the current step.","","Copy-paste to acknowledge each directive now (replace <reason> with a short reason):",...examples,"","Directive content being acknowledged:",...contentLines].join(`
|
|
6464
|
+
`)}async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");_internals185.writeWarnEvent(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let receiptState=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!receiptState.ok){if(config3.mode==="enforce")throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: receipt authority unavailable (${receiptState.code}); refusing to infer acknowledgment from diagnostics`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,reason:receiptState.code});return}let criticalMemberships=selectCurrentArchitectDirectiveMemberships(receiptState.memberships).filter((membership)=>membership.critical);if(criticalMemberships.length===0){clearGateDenialCount(sessionID);return}let unackedMemberships=criticalMemberships.filter((membership)=>!membership.application_marker&&!hasEffectiveGateRelease(membership));if(unackedMemberships.length===0){clearGateDenialCount(sessionID);return}if(config3.mode==="enforce"&&config3.critical_requires_ack){let maxDenials=config3.max_gate_denials??DEFAULT_MAX_GATE_DENIALS,stalenessMs=config3.gate_staleness_ms??DEFAULT_GATE_STALENESS_MS,now2=Date.now(),staleMemberships=selectStaleUnmarkedMemberships(unackedMemberships,now2,stalenessMs);if(staleMemberships.length>0){for(let[traceId,memberships]of groupMembershipsByTrace(staleMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_staleness_release",reason:"configured staleness escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record staleness release")}let stalePairs=new Set(staleMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`));unackedMemberships=unackedMemberships.filter((membership)=>!stalePairs.has(`${membership.trace_id}/${membership.entry_id}`));let staleIds=[...new Set(staleMemberships.map((membership)=>membership.entry_id))];if(clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_staleness_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:staleIds,cleared_pairs:[...stalePairs],age_ms:Math.max(...staleMemberships.map((membership)=>now2-Date.parse(membership.committed_at))),staleness_threshold_ms:stalenessMs}).catch((err)=>{warn(`[knowledge-application-gate] staleness-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)}),unackedMemberships.length===0){clearCriticalShownIds(sessionID);return}}let unackedPairs2=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`),unacked2=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],directiveKey=buildGateDenialDirectiveKey(unackedPairs2),denials=incrementGateDenialCount(sessionID,directiveKey);if(denials>maxDenials){for(let[traceId,memberships]of groupMembershipsByTrace(unackedMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_denial_limit_release",reason:"configured denial-count escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record denial-limit release")}clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_denial_limit_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked2,denial_count:denials,max_gate_denials:maxDenials}).catch((err)=>{warn(`[knowledge-application-gate] denial-limit-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let contents=await loadDirectiveContents(directory,unacked2);throw Error(buildGateDenialMessage(toolName,unackedMemberships,contents))}let unacked=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],unackedPairs=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked,unacknowledged_critical_pairs:unackedPairs}).catch(()=>{})}async function writeWarnEvent2(directory,record3){let filePath=path245.join(directory,".swarm","events.jsonl");await mkdir52(path245.dirname(filePath),{recursive:!0}),await appendFile26(filePath,`${JSON.stringify(record3)}
|
|
6464
6465
|
`,"utf-8")}async function knowledgeApplicationTransformScan(directory,output,sessionID){if(!output?.messages)return;if(!sessionID)return;let target;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i],agent=m.info?.agent;if(typeof agent==="string"&&stripKnownSwarmPrefix(agent)==="architect"){target=m;break}}if(!target)return;let text=(target.parts??[]).map((p)=>typeof p.text==="string"?p.text:"").join(`
|
|
6465
|
-
`);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID},live=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!live.ok){warn(`[knowledge-application-gate] receipt authority unavailable: ${live.code}`);return}for(let ack of acks){if(!ack.trace_id)continue;let key=buildAckDedupKey(sessionID,JSON.stringify([ack.trace_id,ack.id]),ack.result);if(swarmState.knowledgeAckDedup.has(key))continue;let memberships=live.memberships.filter((membership)=>membership.trace_id===ack.trace_id&&membership.entry_id===ack.id&&!membership.application_marker&&!hasEffectiveGateRelease(membership));if(memberships.length===0)continue;let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedAll=!0,newlyCommitted=!1;for(let[traceId,group]of byTrace){let committed=await commitApplicationOutcomeBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,outcome:ack.result,source:"architect_marker",reason:ack.reason}))});if(!committed.ok||committed.rejected.length>0){committedAll=!1;break}if(committed.committed.length>0)newlyCommitted=!0}if(!committedAll)continue;if(addKnowledgeAckDedup(key),!newlyCommitted)continue;try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}var _internals185={knowledgeApplicationGateBefore,knowledgeApplicationTransformScan,HIGH_RISK_TOOLS,writeWarnEvent:writeWarnEvent2,selectCurrentArchitectDirectiveMemberships,selectStaleUnmarkedMemberships};init_knowledge_curator();init_micro_reflector();init_normalize_tool_name();init_pr_subscriptions();init_utils();init_stored_input_args();init_normalize_tool_name();var MAX_OUTPUT_SCAN_BYTES=65536,PR_URL_PATTERN=/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/,_internals186={subscribe,log};function extractPrUrl(text){let match=PR_URL_PATTERN.exec(text.slice(0,MAX_OUTPUT_SCAN_BYTES));if(!match)return null;let owner=match[1],repo=match[2],prNumber=Number.parseInt(match[3],10);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return{repoFullName:`${owner}/${repo}`,prNumber,prUrl:`https://github.com/${owner}/${repo}/pull/${prNumber}`}}function createPrAutoSubscribeHook(directory,config3){return{toolAfter:async(input,output)=>{try{if(!config3.enabled||!config3.auto_subscribe_on_pr_create)return;let sessionID=typeof input.sessionID==="string"?input.sessionID.trim():"";if(!sessionID)return;let tool3=normalizeToolNameLowerCase(input.tool??"");if(tool3!=="bash"&&tool3!=="shell")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args;if(!(typeof args2?.command==="string"?args2.command:"").includes("gh pr create"))return;let outputText2=typeof output.output==="string"?output.output:"";if(!outputText2)return;let prInfo=extractPrUrl(outputText2);if(!prInfo)return;await _internals186.subscribe(directory,{sessionID,prNumber:prInfo.prNumber,repoFullName:prInfo.repoFullName,prUrl:prInfo.prUrl,maxSubscriptions:config3.max_subscriptions}),_internals186.log("[pr-monitor] Auto-subscribed session to created PR",{sessionID,pr:`${prInfo.repoFullName}#${prInfo.prNumber}`})}catch(err){_internals186.log("[pr-monitor] Auto-subscribe failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}}}init_pr_workflow_gate();init_pr_feedback_event_queue();init_utils();init_pr_workflow_auto_wake();init_pr_workflow_gate();init_utils2();import*as fsp6 from"node:fs/promises";var DEFAULT_WAKE_TIMEOUT_MS=5000,DEFAULT_BOUNDARY_QUIET_MS=120000,DEFAULT_BOUNDARY_WATCHDOG_MS=5000,DEFAULT_STATUS_PROBE_TIMEOUT_MS=250,MAX_TRACKED_BOUNDARY_TOOL_PARTS=200,_internals187={readPrWorkflowGateState,claimPrFeedbackMonitorEvents,readPrFeedbackMonitorQueue,observePrWorkflowAutoWakeEvent},DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES=5,DEFAULT_WAKE_COOLDOWN_MS=30000,DEFAULT_BANNER_COOLDOWN_MS=20000,MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION=20,BANNER_PREFIX_PATTERN=/^--- \[(?:PR_REVIEW|PR_FEEDBACK) WORKFLOW ACTIVE/,DEFAULT_TOTAL_WAKE_CEILINGS={S:12,M:54,L:102},MAX_TRACKED_WAKE_SESSIONS=200;function isValidTotalWakeCeiling(value){return value!==void 0&&Number.isInteger(value)&&value>0}function asRecord3(value){return typeof value==="object"&&value!==null?value:void 0}function asArray(value){return Array.isArray(value)?value:[]}function eventEnvelope2(event){return asRecord3(event.properties)??asRecord3(event.data)??{}}function envelopeSessionID(envelope){let info=asRecord3(envelope.info),candidate2=envelope.sessionID??envelope.sessionId??info?.sessionID??info?.sessionId??info?.id;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function normalizeSessionReadiness(value){if(value==="idle"||value==="busy"||value==="retry")return value;let nested=asRecord3(value)?.type;return nested==="idle"||nested==="busy"||nested==="retry"?nested:"unknown"}function extractToolPartID(part){let state=asRecord3(part.state),candidate2=part.id??part.partID??part.callID??state?.id??state?.partID??state?.callID;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function isInFlightToolStatus(value){return value==="pending"||value==="running"}function isTerminalToolStatus(value){return value==="completed"||value==="error"||value==="cancelled"||value==="aborted"}function canonicalGitHubPrUrl5(value){try{let url3=new URL(value),match=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com"||!match)return null;let number7=Number(match[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${match[1].toLowerCase()}/${match[2].toLowerCase()}/pull/${number7}`}catch{return null}}function sameGitHubPr3(left,right){let leftCanonical=canonicalGitHubPrUrl5(left);return leftCanonical!==null&&leftCanonical===canonicalGitHubPrUrl5(right)}function formatQueuedMonitorEventsText(events){if(events.length===0)return"";return["Queued PR monitor events are now authorized for this PR_FEEDBACK workflow and must be treated as feedback inputs for the current round:",...events.map((event)=>`- ${event.type} on ${event.repoFullName}#${event.prNumber}: ${event.message.split(`
|
|
6466
|
+
`);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID},live=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!live.ok){warn(`[knowledge-application-gate] receipt authority unavailable: ${live.code}`);return}for(let ack of acks){if(!ack.trace_id)continue;let key=buildAckDedupKey(sessionID,JSON.stringify([ack.trace_id,ack.id]),ack.result);if(swarmState.knowledgeAckDedup.has(key))continue;let memberships=live.memberships.filter((membership)=>membership.trace_id===ack.trace_id&&membership.entry_id===ack.id&&!membership.application_marker&&!hasEffectiveGateRelease(membership));if(memberships.length===0)continue;let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedAll=!0,newlyCommitted=!1;for(let[traceId,group]of byTrace){let committed=await commitApplicationOutcomeBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,outcome:ack.result,source:"architect_marker",reason:ack.reason}))});if(!committed.ok||committed.rejected.length>0){committedAll=!1;break}if(committed.committed.length>0)newlyCommitted=!0}if(!committedAll)continue;if(addKnowledgeAckDedup(key),!newlyCommitted)continue;try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}var _internals185={knowledgeApplicationGateBefore,knowledgeApplicationTransformScan,HIGH_RISK_TOOLS,writeWarnEvent:writeWarnEvent2,selectCurrentArchitectDirectiveMemberships,selectStaleUnmarkedMemberships,loadDirectiveContents,buildGateDenialMessage};init_knowledge_curator();init_micro_reflector();init_normalize_tool_name();init_pr_subscriptions();init_utils();init_stored_input_args();init_normalize_tool_name();var MAX_OUTPUT_SCAN_BYTES=65536,PR_URL_PATTERN=/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/,_internals186={subscribe,log};function extractPrUrl(text){let match=PR_URL_PATTERN.exec(text.slice(0,MAX_OUTPUT_SCAN_BYTES));if(!match)return null;let owner=match[1],repo=match[2],prNumber=Number.parseInt(match[3],10);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return{repoFullName:`${owner}/${repo}`,prNumber,prUrl:`https://github.com/${owner}/${repo}/pull/${prNumber}`}}function createPrAutoSubscribeHook(directory,config3){return{toolAfter:async(input,output)=>{try{if(!config3.enabled||!config3.auto_subscribe_on_pr_create)return;let sessionID=typeof input.sessionID==="string"?input.sessionID.trim():"";if(!sessionID)return;let tool3=normalizeToolNameLowerCase(input.tool??"");if(tool3!=="bash"&&tool3!=="shell")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args;if(!(typeof args2?.command==="string"?args2.command:"").includes("gh pr create"))return;let outputText2=typeof output.output==="string"?output.output:"";if(!outputText2)return;let prInfo=extractPrUrl(outputText2);if(!prInfo)return;await _internals186.subscribe(directory,{sessionID,prNumber:prInfo.prNumber,repoFullName:prInfo.repoFullName,prUrl:prInfo.prUrl,maxSubscriptions:config3.max_subscriptions}),_internals186.log("[pr-monitor] Auto-subscribed session to created PR",{sessionID,pr:`${prInfo.repoFullName}#${prInfo.prNumber}`})}catch(err){_internals186.log("[pr-monitor] Auto-subscribe failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}}}init_pr_workflow_gate();init_pr_feedback_event_queue();init_utils();init_pr_workflow_auto_wake();init_pr_workflow_gate();init_utils2();import*as fsp6 from"node:fs/promises";var DEFAULT_WAKE_TIMEOUT_MS=5000,DEFAULT_BOUNDARY_QUIET_MS=120000,DEFAULT_BOUNDARY_WATCHDOG_MS=5000,DEFAULT_STATUS_PROBE_TIMEOUT_MS=250,MAX_TRACKED_BOUNDARY_TOOL_PARTS=200,_internals187={readPrWorkflowGateState,claimPrFeedbackMonitorEvents,readPrFeedbackMonitorQueue,observePrWorkflowAutoWakeEvent},DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES=5,DEFAULT_WAKE_COOLDOWN_MS=30000,DEFAULT_BANNER_COOLDOWN_MS=20000,MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION=20,BANNER_PREFIX_PATTERN=/^--- \[(?:PR_REVIEW|PR_FEEDBACK) WORKFLOW ACTIVE/,DEFAULT_TOTAL_WAKE_CEILINGS={S:12,M:54,L:102},MAX_TRACKED_WAKE_SESSIONS=200;function isValidTotalWakeCeiling(value){return value!==void 0&&Number.isInteger(value)&&value>0}function asRecord3(value){return typeof value==="object"&&value!==null?value:void 0}function asArray(value){return Array.isArray(value)?value:[]}function eventEnvelope2(event){return asRecord3(event.properties)??asRecord3(event.data)??{}}function envelopeSessionID(envelope){let info=asRecord3(envelope.info),candidate2=envelope.sessionID??envelope.sessionId??info?.sessionID??info?.sessionId??info?.id;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function normalizeSessionReadiness(value){if(value==="idle"||value==="busy"||value==="retry")return value;let nested=asRecord3(value)?.type;return nested==="idle"||nested==="busy"||nested==="retry"?nested:"unknown"}function extractToolPartID(part){let state=asRecord3(part.state),candidate2=part.id??part.partID??part.callID??state?.id??state?.partID??state?.callID;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function isInFlightToolStatus(value){return value==="pending"||value==="running"}function isTerminalToolStatus(value){return value==="completed"||value==="error"||value==="cancelled"||value==="aborted"}function canonicalGitHubPrUrl5(value){try{let url3=new URL(value),match=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com"||!match)return null;let number7=Number(match[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${match[1].toLowerCase()}/${match[2].toLowerCase()}/pull/${number7}`}catch{return null}}function sameGitHubPr3(left,right){let leftCanonical=canonicalGitHubPrUrl5(left);return leftCanonical!==null&&leftCanonical===canonicalGitHubPrUrl5(right)}function formatQueuedMonitorEventsText(events){if(events.length===0)return"";return["Queued PR monitor events are now authorized for this PR_FEEDBACK workflow and must be treated as feedback inputs for the current round:",...events.map((event)=>`- ${event.type} on ${event.repoFullName}#${event.prNumber}: ${event.message.split(`
|
|
6466
6467
|
`)[0]}`),"Do not expand or replace an already-declared immutable feedback inventory; if these events require a later round, finish or abort the current round first."].join(`
|
|
6467
6468
|
`)}function blockedText(mode,options={}){let lines=[`[${mode} WORKFLOW ACTIVE]`,`The ${mode} workflow gate is still active. Continue with the required structured lanes, evidence, and controller tools until \`complete_pr_workflow\` succeeds.`,`If bounded recovery is exhausted — for example the bind/checkout path is unreachable or settled discovery lanes cannot satisfy their contract — call \`abort_pr_workflow\` (mode: "${mode}", kind: "recovery", reason: "<one-line cause>") to clear an unbound or bound pre-publication gate, or ask the user to run \`/swarm abort-pr-workflow\` for the human force path.`];if(options.suspended)if(options.suspendedReason==="total")lines.push("Auto-resume is suspended because the total wake budget for this workflow has been exhausted. The session will not be re-awoken automatically. Run `/swarm abort-pr-workflow`, call `abort_pr_workflow`, or complete the workflow with `complete_pr_workflow` to publish normally.");else{let max=options.maxConsecutive;lines.push(`Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries (the durable gate \`revision\` did not advance). The session will not be re-awoken automatically. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\` to publish normally.`)}if(options.userInterrupted)lines.push("Auto-resume is paused after a user interruption. The durable workflow gate is preserved, but the plugin will not re-awaken this session. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.");if(options.recovery)lines.push(`Auto-resume is disabled because manual Git recovery is required. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}`);return lines.join(`
|
|
6468
6469
|
`)}function workflowBanner(mode,options={}){let lines=[`--- [${mode} WORKFLOW ACTIVE — output below is not a terminal verdict; \`complete_pr_workflow\` clears the gate on success; if the bind/checkout path is unreachable call \`abort_pr_workflow\` or run \`/swarm abort-pr-workflow\`] ---`];if(options.suspended)if(options.suspendedReason==="total")lines.push("[Auto-resume is suspended because the total wake budget for this workflow has been exhausted. Run `/swarm abort-pr-workflow`, call `abort_pr_workflow`, or complete the workflow with `complete_pr_workflow`.]");else{let max=options.maxConsecutive;lines.push(`[Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\`.]`)}if(options.userInterrupted)lines.push("[Auto-resume paused after a user interruption. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.]");if(options.recovery)lines.push(`[Manual Git recovery required; auto-resume disabled. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}]`);return lines.join(" ")}function createPrWorkflowResponseGate(options){let wakeTimeoutMs=options.wakeTimeoutMs??DEFAULT_WAKE_TIMEOUT_MS,maxConsecutive=options.maxConsecutiveUnproductiveWakes??DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES,wakeCooldownMs=options.wakeCooldownMs??DEFAULT_WAKE_COOLDOWN_MS,bannerCooldownMs=options.bannerCooldownMs??DEFAULT_BANNER_COOLDOWN_MS,boundaryQuietMs=options.boundaryQuietMs??DEFAULT_BOUNDARY_QUIET_MS,boundaryWatchdogMs=options.boundaryWatchdogMs??DEFAULT_BOUNDARY_WATCHDOG_MS,statusProbeTimeoutMs=options.statusProbeTimeoutMs??DEFAULT_STATUS_PROBE_TIMEOUT_MS,now2=options.now??(()=>Date.now()),scheduleTimer=options.scheduleTimer??((callback,delayMs)=>setTimeout(callback,delayMs)),clearScheduledTimer=options.clearScheduledTimer??((timer)=>clearTimeout(timer)),resolveTotalWakeCeiling=(tier)=>{let configured=typeof options.totalWakeCeiling==="number"?options.totalWakeCeiling:options.totalWakeCeiling?.[tier];return isValidTotalWakeCeiling(configured)?configured:DEFAULT_TOTAL_WAKE_CEILINGS[tier]},activeWakeSessions=new Set,wakeBudgets=new Map,bannerStamps=new Map,banneredMessages=new Map,fallbackInjections=new Map,session=options.client?.session,boundaryActivityBySession=new Map,nextBoundaryLifecycleGeneration=1;function allocateBoundaryLifecycleGeneration(){for(let attempts=0;attempts<=boundaryActivityBySession.size;attempts+=1){let candidate2=nextBoundaryLifecycleGeneration;nextBoundaryLifecycleGeneration=candidate2>=Number.MAX_SAFE_INTEGER?1:candidate2+1;let collision=!1;for(let state of boundaryActivityBySession.values())if(state.lifecycleGeneration===candidate2){collision=!0;break}if(!collision)return candidate2}throw Error("Unable to allocate PR workflow boundary generation")}function clearBoundaryTimer(state){if(state.timer!==void 0)clearScheduledTimer(state.timer),state.timer=void 0}function clearBoundaryActivity(sessionID,dropState=!0){let state=boundaryActivityBySession.get(sessionID);if(!state)return;if(clearBoundaryTimer(state),state.quietDeadlineAt=void 0,state.watchdogDeadlineAt=void 0,dropState)boundaryActivityBySession.delete(sessionID)}function evictBoundaryActivityIfOverBound(currentSessionID){while(boundaryActivityBySession.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey,oldestSeenAt=Number.POSITIVE_INFINITY;for(let[key,state]of boundaryActivityBySession){if(key===currentSessionID||activeWakeSessions.has(key))continue;if(state.lastObservedAt<oldestSeenAt)oldestSeenAt=state.lastObservedAt,oldestKey=key}if(oldestKey===void 0)break;clearBoundaryActivity(oldestKey)}}function getOrCreateBoundaryActivity(sessionID){let state=boundaryActivityBySession.get(sessionID);if(state)return state;return state={lifecycleGeneration:allocateBoundaryLifecycleGeneration(),lastParentActivityAt:0,lastObservedAt:now2(),lastHostStatus:"unknown",hostStatusGeneration:0,activeToolParts:new Map,terminalToolParts:new Map,removedToolParts:new Map,timerGeneration:0},boundaryActivityBySession.set(sessionID,state),evictBoundaryActivityIfOverBound(sessionID),state}function getLiveBoundaryActivity(sessionID,expectedGeneration){let state=boundaryActivityBySession.get(sessionID);return state&&state.lifecycleGeneration===expectedGeneration?state:void 0}function rememberBoundedKeyedTimestamp(map3,key,stamp){map3.delete(key),map3.set(key,stamp);while(map3.size>MAX_TRACKED_BOUNDARY_TOOL_PARTS){let oldest=map3.keys().next().value;if(typeof oldest!=="string")break;map3.delete(oldest)}}function rememberActiveToolPart(state,partID,status){state.activeToolParts.delete(partID),state.activeToolParts.set(partID,status);while(state.activeToolParts.size>MAX_TRACKED_BOUNDARY_TOOL_PARTS){let oldest=state.activeToolParts.keys().next().value;if(typeof oldest!=="string")break;state.activeToolParts.delete(oldest)}}function armBoundaryLeaseTimer(sessionID,state,currentNow){let quietDeadlineAt=state.quietDeadlineAt??currentNow+Math.max(0,boundaryQuietMs),watchdogDeadlineAt=state.watchdogDeadlineAt??currentNow+Math.max(0,boundaryWatchdogMs);state.quietDeadlineAt=quietDeadlineAt,state.watchdogDeadlineAt=watchdogDeadlineAt;let nextWakeAt=quietDeadlineAt>currentNow?Math.min(quietDeadlineAt,watchdogDeadlineAt):watchdogDeadlineAt;if(nextWakeAt<=currentNow&&(state.activeToolParts.size>0||state.lastHostStatus==="busy"||state.lastHostStatus==="retry"))nextWakeAt=currentNow+Math.max(1,boundaryWatchdogMs),state.quietDeadlineAt=nextWakeAt,state.watchdogDeadlineAt=nextWakeAt;let delayMs=Math.max(0,nextWakeAt-currentNow);clearBoundaryTimer(state),state.timerGeneration+=1;let{timerGeneration:generation,lifecycleGeneration:boundaryGeneration}=state;if(state.timer=scheduleTimer(()=>{runBoundaryLeaseTimer(sessionID,generation,boundaryGeneration)},delayMs),typeof state.timer.unref==="function")state.timer.unref()}function noteParentActivity(sessionID,stamp){let state=getOrCreateBoundaryActivity(sessionID);if(state.lastObservedAt=stamp,state.lastParentActivityAt=stamp,state.quietDeadlineAt!==void 0||state.watchdogDeadlineAt!==void 0)state.quietDeadlineAt=stamp+Math.max(0,boundaryQuietMs),state.watchdogDeadlineAt=stamp+Math.max(0,boundaryWatchdogMs),armBoundaryLeaseTimer(sessionID,state,stamp)}function observeHostStatus(state,readiness,stamp){state.lastObservedAt=stamp,state.lastHostStatus=readiness,state.hostStatusGeneration+=1}function observeToolPartState(sessionID,part,removed,stamp){let partID=extractToolPartID(part);if(!partID)return;let state=getOrCreateBoundaryActivity(sessionID);if(state.lastObservedAt=stamp,removed){state.activeToolParts.delete(partID),rememberBoundedKeyedTimestamp(state.removedToolParts,partID,stamp),noteParentActivity(sessionID,stamp);return}let rawStatus=asRecord3(part.state)?.status??part.status;if(isInFlightToolStatus(rawStatus)){if(state.terminalToolParts.has(partID)||state.removedToolParts.has(partID))return;rememberActiveToolPart(state,partID,rawStatus),noteParentActivity(sessionID,stamp);return}if(!isTerminalToolStatus(rawStatus))return;state.activeToolParts.delete(partID),rememberBoundedKeyedTimestamp(state.terminalToolParts,partID,stamp),noteParentActivity(sessionID,stamp)}function observeBoundaryActivity(rawEvent){let event2=asRecord3(rawEvent);if(!event2)return{};let envelope=eventEnvelope2(event2),sessionID=envelopeSessionID(envelope),stamp=now2();if((event2.type==="session.deleted"||event2.type==="session.removed")&&sessionID)return clearBoundaryActivity(sessionID),{sessionID};if(event2.type==="session.status"&&sessionID){let state=getOrCreateBoundaryActivity(sessionID);return observeHostStatus(state,normalizeSessionReadiness(envelope.status),stamp),{sessionID,boundaryGeneration:state.lifecycleGeneration}}if(event2.type==="session.idle"&&sessionID){let state=getOrCreateBoundaryActivity(sessionID);return observeHostStatus(state,"idle",stamp),{sessionID,boundaryGeneration:state.lifecycleGeneration}}if(event2.type==="message.updated"){let info=asRecord3(envelope.info),infoSessionID=envelopeSessionID(info??{});if(info?.role==="assistant"&&infoSessionID){noteParentActivity(infoSessionID,stamp);for(let partValue of asArray(info.parts??envelope.parts)){let part=asRecord3(partValue);if(!part||part.type!=="tool")continue;observeToolPartState(infoSessionID,part,!1,stamp)}return{sessionID:infoSessionID}}return{sessionID:infoSessionID??sessionID}}if(event2.type==="message.part.updated"||event2.type==="message.part.removed"){let part=asRecord3(envelope.part),partSessionID=envelopeSessionID(part??{})??sessionID;if(!part||!partSessionID)return{sessionID:partSessionID};if(part.type==="text"||part.type==="tool"||part.type==="step-finish")noteParentActivity(partSessionID,stamp);if(part.type==="tool")observeToolPartState(partSessionID,part,event2.type==="message.part.removed",stamp);return{sessionID:partSessionID}}return{sessionID}}function evictIfOverBound(currentSessionID){while(wakeBudgets.size>MAX_TRACKED_WAKE_SESSIONS){let lruKey,lruWakeAt=Number.POSITIVE_INFINITY,neverWokenKey;for(let[key,budget]of wakeBudgets){if(budget.suspended||key===currentSessionID||activeWakeSessions.has(key))continue;if(budget.lastWakeAt<=0){if(neverWokenKey===void 0)neverWokenKey=key;continue}if(budget.lastWakeAt<lruWakeAt)lruWakeAt=budget.lastWakeAt,lruKey=key}let evicted=lruKey??neverWokenKey;if(evicted===void 0)break;wakeBudgets.delete(evicted)}}function evictBannerDedupeMapsIfOverBound(){while(bannerStamps.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=bannerStamps.keys().next().value;if(oldestKey===void 0)break;bannerStamps.delete(oldestKey)}while(banneredMessages.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=banneredMessages.keys().next().value;if(oldestKey===void 0)break;banneredMessages.delete(oldestKey)}while(fallbackInjections.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=fallbackInjections.keys().next().value;if(oldestKey===void 0)break;fallbackInjections.delete(oldestKey)}}function resetBudget(sessionID){wakeBudgets.delete(sessionID),bannerStamps.delete(sessionID),banneredMessages.delete(sessionID),fallbackInjections.delete(sessionID),clearBoundaryActivity(sessionID)}async function appendWakeSuspendedEvent(fields){try{let eventsPath=validateSwarmPath(options.directory,"events.jsonl"),suspendedEvent={type:"pr_workflow_wake_suspended",timestamp:new Date().toISOString(),sessionID:fields.sessionID,mode:fields.mode,suspendedReason:fields.suspendedReason,consecutiveUnproductive:fields.consecutiveUnproductive,totalWakes:fields.totalWakes,tier:fields.tier,maxConsecutiveUnproductiveWakes:maxConsecutive,totalWakeCeiling:resolveTotalWakeCeiling(fields.tier)};await fsp6.appendFile(eventsPath,`${JSON.stringify(suspendedEvent)}
|
|
@@ -6479,7 +6480,7 @@ ${output.text}`},_inspectWakeBudget:(sessionID)=>wakeBudgets.get(sessionID),_ins
|
|
|
6479
6480
|
`)}function injectReviewerManifestPrompt(args2,scope,hash5){try{if(!args2||typeof args2!=="object")return;let record3=args2;if(typeof record3.prompt!=="string")return;if(record3.prompt.includes("<reviewer_scope_manifest>"))return;let deliveryByPath=new Map(scope.delivery.map((e)=>[e.path,e.mode])),entries=scope.files.map((file3)=>{let fingerprintLine=scope.content.split(`
|
|
6480
6481
|
`).map((line)=>{try{let parsed=JSON.parse(line);return typeof parsed.path==="string"&&parsed.path===file3?parsed:null}catch{return null}}).find((parsed)=>parsed!==null),state=fingerprintLine?.state==="deleted"?"deleted":"file";return{path:file3,state,bytes:typeof fingerprintLine?.bytes==="number"?fingerprintLine.bytes:void 0,sha256:typeof fingerprintLine?.sha256==="string"?fingerprintLine.sha256:void 0,mode:deliveryByPath.get(file3)??"manual"}}),block=reviewerManifestPromptBlock({description:REVIEWER_TASK_SCOPE_DESCRIPTION,hash:hash5,headSha:scope.headSha,workspaceIdentity:scope.workspaceIdentity,entries});record3.prompt=`${block}
|
|
6481
6482
|
|
|
6482
|
-
${record3.prompt}`}catch{}}async function beginApprovedReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return null;let target=lifecycleTarget(input.args);if(target==="coder"){let binding=getScopeBindingForParentDispatch({parentSessionId:input.parentSessionID,dispatchCallId:input.callID});if(!binding)return null;if(binding.taskId!==taskId){if(standardWorktreeByCallID.has(input.callID))try{await abortStandardWorktreeDispatch(input.callID,"cancelled",input.directory)}catch{}throw typedReviewerScopeError("REVIEWER_SCOPE_BINDING_MISMATCH",`task ${taskId}: the activated scope binding names task ${binding.taskId} for this dispatch (retryable=true, responsible: architect). ACTION[architect]: re-declare scope for the exact task and redispatch`)}let capture=resolveReviewerCaptureDirectory({binding,callID:input.callID,ambient:input.directory});if(!capture.ok){if(standardWorktreeByCallID.has(input.callID))try{await abortStandardWorktreeDispatch(input.callID,"cancelled",input.directory)}catch{}throw typedReviewerScopeError("REVIEWER_SCOPE_BINDING_MISMATCH",`task ${taskId}: coder workspace root could not be bound (${capture.detail}) (retryable=true, responsible: architect). ACTION[architect]: verify the worktree lane/scope binding for this dispatch, then redispatch`)}let rawArgs=input.args&&typeof input.args==="object"?input.args:null;return startReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,background:rawArgs?.background===!0||rawArgs?.background==="true",declaredFiles:binding.files,captureDirectory:capture.directory,workspaceIdentity:capture.identity})?"coder_started":null}if(target==="reviewer"){let ready=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId});if(!ready){let noChange=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"no_change"});if(noChange)throw typedReviewerScopeError("REVIEWER_SCOPE_NO_CHANGE",`task ${taskId} generation ${noChange.generation}: the coder made zero guardrail-observed writes and the workspace diff is empty — no reviewer pass is owed (retryable=true, responsible: architect). ACTION[architect]: satisfy acceptance deterministically, or re-dispatch the coder if changes were intended`);let pending=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"mergeback_pending"});if(pending)throw typedReviewerScopeError("REVIEWER_SCOPE_MERGEBACK_PENDING",`task ${taskId} generation ${pending.generation}: lane merge-back has not been verified against the primary checkout yet (retryable=true, responsible: architect). ACTION[architect]: wait for the merge-back advisory, then re-dispatch the reviewer`);let mismatch=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"mergeback_mismatch"});if(mismatch){let mergebackReason=mismatch.mergeback&&"failedAt"in mismatch.mergeback?mismatch.mergeback.reason:"unverified";throw typedReviewerScopeError("REVIEWER_SCOPE_MERGEBACK_MISMATCH",`task ${taskId} generation ${mismatch.generation}: merge-back verification failed (${mergebackReason}) (retryable=true, responsible: architect). ACTION[architect]: resolve the lane merge conflict or re-dispatch the coder`)}throw typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: coder post-write fingerprints are incomplete or changed before reviewer dispatch (retryable=false, responsible: architect)`)}let freshFirst=await withCaptureRetry((_attempt,deadlineAt)=>generationFingerprintsAreCurrent(peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId})??ready,{deadlineAt}),(outcome)=>outcome.current===!1&&outcome.reason==="capture_failed"&&outcome.failure.retryable);if(freshFirst.value.current===!1){let outcome=freshFirst.value;if(outcome.reason==="genuine_drift")discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID});throw freshnessDenial(outcome,ready,freshFirst.attemptsRun)}let build=await withCaptureRetry((_attempt,deadlineAt)=>buildReviewerTaskScope(input.directory,ready.modifiedFiles,input.maxBytes,{taskId:ready.taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation},{deadlineAt}),(result)=>result.ok===!1&&result.retryable);if(!build.value.ok){let failure=build.value;throw typedReviewerScopeError(failure.retryable?"REVIEWER_CAPTURE_RETRY_EXHAUSTED":"REVIEWER_CAPTURE_FAILED",`task ${ready.taskId} generation ${ready.generation}${failure.file?`: file ${failure.file}`:""}: scope build failed (${failure.code}, retryable=${failure.retryable}, attempts=${build.attemptsRun}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${failure.retryable?"re-dispatch the reviewer to retry capture, or route explicit manual review":`resolve the ${failure.code} condition, then re-dispatch the reviewer or route explicit manual review`}`)}let current=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId}),exactGenerationStillCurrent=current!==null&¤t.coderCallID===ready.coderCallID&¤t.generation===ready.generation&¤t.sessionIncarnation===ready.sessionIncarnation&&isReviewerScopeGenerationCurrent({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation});if(!current||!exactGenerationStillCurrent||!generationFingerprintsAreCurrent(current,{deadlineAt:Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS}).current||!scopeMatchesGenerationFingerprints(build.value.scope,current))throw discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId} generation ${ready.generation}: exact reviewer dispatch scope changed during capture (retryable=false, responsible: architect)`);let claimed=claimReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID});if(!claimed||claimed.coderCallID!==ready.coderCallID||claimed.generation!==ready.generation||claimed.sessionIncarnation!==ready.sessionIncarnation)throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: exact reviewer dispatch scope could not be claimed (retryable=false, responsible: architect)`);let dispatchHash=computeScopeFingerprint(build.value.scope.content,build.value.scope.description).hash;if(!attachReviewerScopeGenerationDispatchSnapshot({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID,snapshot:{hash:dispatchHash,description:build.value.scope.description,files:[...build.value.scope.files],headSha:build.value.scope.headSha,taskId:claimed.taskId,coderCallID:claimed.coderCallID,generation:claimed.generation,sessionIncarnation:claimed.sessionIncarnation}}))throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: exact reviewer dispatch scope could not be captured (retryable=false, responsible: architect)`);return injectReviewerManifestPrompt(input.args,build.value.scope,dispatchHash),"reviewer_claimed"}return null}async function completeReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;if(lifecycleTarget(input.args)!=="coder")return null;let result=classifyTaskResult(input.output);if(result==="running")return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,coderCallID:input.callID}),null;if(result==="non_success")return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID});if(!generation)return null;if(generation.status!=="collecting")return null;if(generation.modifiedFiles.length===0){let status=await verifyWorkingTreeClean(generation.captureDirectory);if(status==="clean")return markReviewerScopeGenerationNoChange({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID})?"coder_no_change":null;return pushAdvisory(ensureAgentSession(input.parentSessionID),`REVIEWER_SCOPE_UNATTRIBUTED_CHANGE: task ${taskId} generation ${generation.generation}: the workspace diff was ${status==="dirty"?"dirty":"not verifiable"} while zero guardrail-observed writes were routed. ACTION[architect]: inspect the workspace for writes that bypassed guardrails, then re-dispatch the coder`),null}if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file3)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file3)))){let missing=generation.modifiedFiles.length-generation.modifiedFileFingerprints.length;return pushAdvisory(ensureAgentSession(input.parentSessionID),`REVIEWER_CAPTURE_INCOMPLETE: task ${taskId} generation ${generation.generation}: ${missing} file(s) have no stored fingerprint after coder completion; the generation is retained but not reviewable yet. ACTION[architect]: retry the coder so capture re-runs, or inspect ${generation.captureFailures.map((entry)=>sanitizeDiagnosticText(entry.file,120)).slice(0,5).join(", ")} capture failures (responsible: architect)`),null}let laneIdentity=generation.workspaceIdentity,primaryIdentity=canonicalWorkspaceIdentity(input.directory);if(laneIdentity&&primaryIdentity&&laneIdentity!==primaryIdentity)return markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;return markReviewerScopeGenerationReady({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,primaryWorkspaceIdentity:primaryIdentity??void 0})?"coder_ready":null}init_reviewer_directive_compliance();init_schema();init_bun_compat();init_logger();var import_picomatch2=__toESM(require_picomatch2(),1);import{existsSync as existsSync128,readdirSync as readdirSync35,readFileSync as readFileSync96,statSync as statSync54}from"node:fs";import*as path246 from"node:path";var PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path246.resolve(directory),resolved=path246.resolve(baseDir,concrete),rel=path246.relative(baseDir,resolved);if(rel.startsWith("..")||path246.isAbsolute(rel))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path246.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path246.join(dir,name);if(existsSync128(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve99)=>setTimeout(()=>resolve99("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries;try{entries=readdirSync35(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(visited>=GREP_MAX_FILES)return;let fullPath=path246.join(dir,entry.name),relPath=path246.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync54(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync96(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path246.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path246.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();var _internals189={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key))continue;let existing=verdictsByPair.get(key)??[];existing.push(verdict),verdictsByPair.set(key,existing)}let pending=[];for(let[key,directive]of verifyByPair){let matching=verdictsByPair.get(key)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals189.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=first.prior_terminal_outcome==="violated"&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals189.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected.entry_id||void 0,code:rejected.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals189.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals189.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")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 directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}init_constants();init_schema();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_normalize_tool_name();init_pr_workflow_gate();init_write_target_resolver();import*as path247 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,fallbackDirectory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown",agentRole=stripKnownSwarmPrefix(agentName);if(agentRole===ORCHESTRATOR_NAME)return;if(agentRole!=="coder")return;let directory=_internals190.resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory),targets=_internals190.resolveWriteTargets(toolName,output.args,{directory});if(targets.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${agentName} invoked ${toolName}: ${targets.reason}`);if(targets.paths.length===0)return;let taskId=_internals190.resolveTaskId(session),seamBinding=taskId&&_internals190.resolveAuthorizedScopeBinding!==resolveAuthorizedScopeBinding?_internals190.resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionId}):null,resolution=seamBinding?{status:"found",binding:seamBinding}:taskId?_internals190.resolveAuthorizedScopeBindingDetailed({directory,taskId,activeSessionId:sessionId}):_internals190.resolveAuthorizedScopeBindingForSessionDetailed({directory,activeSessionId:sessionId}),binding=resolution.status==="found"?resolution.binding:null;if(!binding){if(binding=_internals190.getAuthorizedPrFeedbackScopeBinding({directory,activeSessionId:sessionId,taskId:taskId??void 0})??_internals190.resolveAuthorizedPrFeedbackScopeBindingFromDisk({directory,activeSessionId:sessionId,taskId:taskId??void 0}),binding&&!await _internals190.validatePrFeedbackScopeBinding(directory,binding))binding=null}if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null;if(!declaredScope||declaredScope.length===0){let durableDiagnostic=formatScopeResolutionDiagnostic({resolution,taskId,sessionId});if(durableDiagnostic)denyWithArchitectAdvisory(durableDiagnostic,session,injectAdvisory,swarmState);let mismatch=_internals190.describeScopeWorkspaceMismatch({directory,activeSessionId:sessionId,taskId});if(mismatch)denyWithArchitectAdvisory(`${mismatch} ${agentName} cannot invoke ${toolName} for task ${taskId??"unknown"}. ACTION[architect]: redeclare the exact scope against the reported active lane root with replace_existing=true, then dispatch a new Task call.`,session,injectAdvisory,swarmState);denyWithArchitectAdvisory(`SCOPE_NOT_DECLARED: ${agentName} cannot invoke ${toolName} without a validated scope for task ${taskId??"unknown"}. ACTION[architect]: call declare_scope with the exact workspace-relative paths and replace_existing=true, then dispatch a new Task call.`,session,injectAdvisory,swarmState)}for(let rawPath of targets.paths){let filePath=sanitizePath(rawPath),absoluteTarget=path247.resolve(directory,filePath);if(!isPathIdentityWithin(absoluteTarget,directory)){let fallbackRelative=isPathIdentityWithin(absoluteTarget,fallbackDirectory)?path247.relative(fallbackDirectory,absoluteTarget).replace(/\\/g,"/"):null,safeRetry=fallbackRelative?`detected workspace-relative path ${JSON.stringify(sanitizeDiagnosticText(fallbackRelative))}; retry exactly that relative path under the active root`:"no safe workspace-relative retry was detected; stop and correct the command or lane root";denyWithArchitectAdvisory(`SCOPE_ROOT_ESCAPE: attempted target ${JSON.stringify(sanitizeDiagnosticText(filePath))} leaves active root ${JSON.stringify(sanitizeDiagnosticText(directory))}; ${safeRetry}. ACTION[architect]: verify the active lane root, redeclare only the exact relative path with replace_existing=true, and dispatch a new Task call.`,session,injectAdvisory,swarmState)}if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path247.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path247.resolve(dir,scope);return isPathIdentityWithin(resolvedFile,resolvedScope)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}var _internals190={sanitizePath,resolveWriteTargets:resolveWriteTargets2,resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBinding,resolveAuthorizedScopeBindingForSession,getAuthorizedPrFeedbackScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk,validatePrFeedbackScopeBinding,resolveSessionWorkspaceDirectory,describeScopeWorkspaceMismatch,resolveTaskId:(session)=>session?.currentTaskId??null};function denyWithArchitectAdvisory(message,session,injectAdvisory,state){if(session)session.lastScopeViolation=message,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[architectSessionId,architectSession]of state.agentSessions){let role=state.activeAgent.get(architectSessionId)??architectSession.agentName;if(stripKnownSwarmPrefix(role)!==ORCHESTRATOR_NAME)continue;try{injectAdvisory(architectSessionId,`[SCOPE GUARD] ${message}`)}catch{}break}throw Error(message)}function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let taskLabel2=taskId??"unknown",safeAgentName=sanitizeDiagnosticText(agentName,128),safeFilePath=sanitizeDiagnosticText(filePath,256),safeScope=scopeEntries.slice(0,3).map((entry)=>sanitizeDiagnosticText(entry,128)).join(", "),violationMessage=`SCOPE_VIOLATION: SCOPE VIOLATION: ${safeAgentName} attempted to modify '${safeFilePath}' which is not in declared scope for task ${taskLabel2}. Declared scope: [${safeScope}${scopeEntries.length>3?"...":""}]. Coder: correct a mistaken target; otherwise stop and ask the architect to expand declare_scope and dispatch a new Task call.`;denyWithArchitectAdvisory(violationMessage,session,injectAdvisory,state)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
|
|
6483
|
+
${record3.prompt}`}catch{}}async function beginApprovedReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return null;let target=lifecycleTarget(input.args);if(target==="coder"){let binding=getScopeBindingForParentDispatch({parentSessionId:input.parentSessionID,dispatchCallId:input.callID});if(!binding)return null;if(binding.taskId!==taskId){if(standardWorktreeByCallID.has(input.callID))try{await abortStandardWorktreeDispatch(input.callID,"cancelled",input.directory)}catch{}throw typedReviewerScopeError("REVIEWER_SCOPE_BINDING_MISMATCH",`task ${taskId}: the activated scope binding names task ${binding.taskId} for this dispatch (retryable=true, responsible: architect). ACTION[architect]: re-declare scope for the exact task and redispatch`)}let capture=resolveReviewerCaptureDirectory({binding,callID:input.callID,ambient:input.directory});if(!capture.ok){if(standardWorktreeByCallID.has(input.callID))try{await abortStandardWorktreeDispatch(input.callID,"cancelled",input.directory)}catch{}throw typedReviewerScopeError("REVIEWER_SCOPE_BINDING_MISMATCH",`task ${taskId}: coder workspace root could not be bound (${capture.detail}) (retryable=true, responsible: architect). ACTION[architect]: verify the worktree lane/scope binding for this dispatch, then redispatch`)}let rawArgs=input.args&&typeof input.args==="object"?input.args:null;return startReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,background:rawArgs?.background===!0||rawArgs?.background==="true",declaredFiles:binding.files,captureDirectory:capture.directory,workspaceIdentity:capture.identity})?"coder_started":null}if(target==="reviewer"){let ready=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId});if(!ready){let noChange=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"no_change"});if(noChange)throw typedReviewerScopeError("REVIEWER_SCOPE_NO_CHANGE",`task ${taskId} generation ${noChange.generation}: the coder made zero guardrail-observed writes and the workspace diff is empty — no reviewer pass is owed (retryable=true, responsible: architect). ACTION[architect]: satisfy acceptance deterministically, or re-dispatch the coder if changes were intended`);let pending=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"mergeback_pending"});if(pending)throw typedReviewerScopeError("REVIEWER_SCOPE_MERGEBACK_PENDING",`task ${taskId} generation ${pending.generation}: lane merge-back has not been verified against the primary checkout yet (retryable=true, responsible: architect). ACTION[architect]: wait for the merge-back advisory, then re-dispatch the reviewer`);let mismatch=peekReviewerScopeGenerationByStatus({parentSessionID:input.parentSessionID,taskId,status:"mergeback_mismatch"});if(mismatch){let mergebackReason=mismatch.mergeback&&"failedAt"in mismatch.mergeback?mismatch.mergeback.reason:"unverified";throw typedReviewerScopeError("REVIEWER_SCOPE_MERGEBACK_MISMATCH",`task ${taskId} generation ${mismatch.generation}: merge-back verification failed (${mergebackReason}) (retryable=true, responsible: architect). ACTION[architect]: resolve the lane merge conflict or re-dispatch the coder`)}throw typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: coder post-write fingerprints are incomplete or changed before reviewer dispatch (retryable=false, responsible: architect)`)}let freshFirst=await withCaptureRetry((_attempt,deadlineAt)=>generationFingerprintsAreCurrent(peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId})??ready,{deadlineAt}),(outcome)=>outcome.current===!1&&outcome.reason==="capture_failed"&&outcome.failure.retryable);if(freshFirst.value.current===!1){let outcome=freshFirst.value;if(outcome.reason==="genuine_drift")discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID});throw freshnessDenial(outcome,ready,freshFirst.attemptsRun)}let build=await withCaptureRetry((_attempt,deadlineAt)=>buildReviewerTaskScope(input.directory,ready.modifiedFiles,input.maxBytes,{taskId:ready.taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation},{deadlineAt}),(result)=>result.ok===!1&&result.retryable);if(!build.value.ok){let failure=build.value;throw typedReviewerScopeError(failure.retryable?"REVIEWER_CAPTURE_RETRY_EXHAUSTED":"REVIEWER_CAPTURE_FAILED",`task ${ready.taskId} generation ${ready.generation}${failure.file?`: file ${failure.file}`:""}: scope build failed (${failure.code}, retryable=${failure.retryable}, attempts=${build.attemptsRun}/${REVIEWER_SCOPE_CAPTURE_ATTEMPTS}, responsible: architect). ACTION[architect]: ${failure.retryable?"re-dispatch the reviewer to retry capture, or route explicit manual review":`resolve the ${failure.code} condition, then re-dispatch the reviewer or route explicit manual review`}`)}let current=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId}),exactGenerationStillCurrent=current!==null&¤t.coderCallID===ready.coderCallID&¤t.generation===ready.generation&¤t.sessionIncarnation===ready.sessionIncarnation&&isReviewerScopeGenerationCurrent({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation});if(!current||!exactGenerationStillCurrent||!generationFingerprintsAreCurrent(current,{deadlineAt:Date.now()+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS}).current||!scopeMatchesGenerationFingerprints(build.value.scope,current))throw discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId} generation ${ready.generation}: exact reviewer dispatch scope changed during capture (retryable=false, responsible: architect)`);let claimed=claimReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID});if(!claimed||claimed.coderCallID!==ready.coderCallID||claimed.generation!==ready.generation||claimed.sessionIncarnation!==ready.sessionIncarnation)throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: exact reviewer dispatch scope could not be claimed (retryable=false, responsible: architect)`);let dispatchHash=computeScopeFingerprint(build.value.scope.content,build.value.scope.description).hash;if(!attachReviewerScopeGenerationDispatchSnapshot({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID,snapshot:{hash:dispatchHash,description:build.value.scope.description,files:[...build.value.scope.files],headSha:build.value.scope.headSha,taskId:claimed.taskId,coderCallID:claimed.coderCallID,generation:claimed.generation,sessionIncarnation:claimed.sessionIncarnation}}))throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),typedReviewerScopeError("REVIEWER_SCOPE_STALE",`task ${taskId}: exact reviewer dispatch scope could not be captured (retryable=false, responsible: architect)`);return injectReviewerManifestPrompt(input.args,build.value.scope,dispatchHash),"reviewer_claimed"}return null}async function completeReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;if(lifecycleTarget(input.args)!=="coder")return null;let result=classifyTaskResult(input.output);if(result==="running")return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,coderCallID:input.callID}),null;if(result==="non_success")return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID});if(!generation)return null;if(generation.status!=="collecting")return null;if(generation.modifiedFiles.length===0){let status=await verifyWorkingTreeClean(generation.captureDirectory);if(status==="clean")return markReviewerScopeGenerationNoChange({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID})?"coder_no_change":null;return pushAdvisory(ensureAgentSession(input.parentSessionID),`REVIEWER_SCOPE_UNATTRIBUTED_CHANGE: task ${taskId} generation ${generation.generation}: the workspace diff was ${status==="dirty"?"dirty":"not verifiable"} while zero guardrail-observed writes were routed. ACTION[architect]: inspect the workspace for writes that bypassed guardrails, then re-dispatch the coder`),null}if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file3)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file3)))){let missing=generation.modifiedFiles.length-generation.modifiedFileFingerprints.length;return pushAdvisory(ensureAgentSession(input.parentSessionID),`REVIEWER_CAPTURE_INCOMPLETE: task ${taskId} generation ${generation.generation}: ${missing} file(s) have no stored fingerprint after coder completion; the generation is retained but not reviewable yet. ACTION[architect]: retry the coder so capture re-runs, or inspect ${generation.captureFailures.map((entry)=>sanitizeDiagnosticText(entry.file,120)).slice(0,5).join(", ")} capture failures (responsible: architect)`),null}let laneIdentity=generation.workspaceIdentity,primaryIdentity=canonicalWorkspaceIdentity(input.directory);if(laneIdentity&&primaryIdentity&&laneIdentity!==primaryIdentity)return markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;return markReviewerScopeGenerationReady({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,primaryWorkspaceIdentity:primaryIdentity??void 0})?"coder_ready":null}init_reviewer_directive_compliance();init_schema();init_bun_compat();init_logger();var import_picomatch2=__toESM(require_picomatch2(),1);import{existsSync as existsSync129,readdirSync as readdirSync35,readFileSync as readFileSync96,statSync as statSync54}from"node:fs";import*as path246 from"node:path";var PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path246.resolve(directory),resolved=path246.resolve(baseDir,concrete),rel=path246.relative(baseDir,resolved);if(rel.startsWith("..")||path246.isAbsolute(rel))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path246.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path246.join(dir,name);if(existsSync129(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve99)=>setTimeout(()=>resolve99("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries;try{entries=readdirSync35(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(visited>=GREP_MAX_FILES)return;let fullPath=path246.join(dir,entry.name),relPath=path246.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync54(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync96(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path246.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path246.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();var _internals189={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key))continue;let existing=verdictsByPair.get(key)??[];existing.push(verdict),verdictsByPair.set(key,existing)}let pending=[];for(let[key,directive]of verifyByPair){let matching=verdictsByPair.get(key)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals189.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=first.prior_terminal_outcome==="violated"&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals189.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected.entry_id||void 0,code:rejected.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals189.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals189.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")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 directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}init_constants();init_schema();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_normalize_tool_name();init_pr_workflow_gate();init_write_target_resolver();import*as path247 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,fallbackDirectory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown",agentRole=stripKnownSwarmPrefix(agentName);if(agentRole===ORCHESTRATOR_NAME)return;if(agentRole!=="coder")return;let directory=_internals190.resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory),targets=_internals190.resolveWriteTargets(toolName,output.args,{directory});if(targets.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${agentName} invoked ${toolName}: ${targets.reason}`);if(targets.paths.length===0)return;let taskId=_internals190.resolveTaskId(session),seamBinding=taskId&&_internals190.resolveAuthorizedScopeBinding!==resolveAuthorizedScopeBinding?_internals190.resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionId}):null,resolution=seamBinding?{status:"found",binding:seamBinding}:taskId?_internals190.resolveAuthorizedScopeBindingDetailed({directory,taskId,activeSessionId:sessionId}):_internals190.resolveAuthorizedScopeBindingForSessionDetailed({directory,activeSessionId:sessionId}),binding=resolution.status==="found"?resolution.binding:null;if(!binding){if(binding=_internals190.getAuthorizedPrFeedbackScopeBinding({directory,activeSessionId:sessionId,taskId:taskId??void 0})??_internals190.resolveAuthorizedPrFeedbackScopeBindingFromDisk({directory,activeSessionId:sessionId,taskId:taskId??void 0}),binding&&!await _internals190.validatePrFeedbackScopeBinding(directory,binding))binding=null}if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null;if(!declaredScope||declaredScope.length===0){let durableDiagnostic=formatScopeResolutionDiagnostic({resolution,taskId,sessionId});if(durableDiagnostic)denyWithArchitectAdvisory(durableDiagnostic,session,injectAdvisory,swarmState);let mismatch=_internals190.describeScopeWorkspaceMismatch({directory,activeSessionId:sessionId,taskId});if(mismatch)denyWithArchitectAdvisory(`${mismatch} ${agentName} cannot invoke ${toolName} for task ${taskId??"unknown"}. ACTION[architect]: redeclare the exact scope against the reported active lane root with replace_existing=true, then dispatch a new Task call.`,session,injectAdvisory,swarmState);denyWithArchitectAdvisory(`SCOPE_NOT_DECLARED: ${agentName} cannot invoke ${toolName} without a validated scope for task ${taskId??"unknown"}. ACTION[architect]: call declare_scope with the exact workspace-relative paths and replace_existing=true, then dispatch a new Task call.`,session,injectAdvisory,swarmState)}for(let rawPath of targets.paths){let filePath=sanitizePath(rawPath),absoluteTarget=path247.resolve(directory,filePath);if(!isPathIdentityWithin(absoluteTarget,directory)){let fallbackRelative=isPathIdentityWithin(absoluteTarget,fallbackDirectory)?path247.relative(fallbackDirectory,absoluteTarget).replace(/\\/g,"/"):null,safeRetry=fallbackRelative?`detected workspace-relative path ${JSON.stringify(sanitizeDiagnosticText(fallbackRelative))}; retry exactly that relative path under the active root`:"no safe workspace-relative retry was detected; stop and correct the command or lane root";denyWithArchitectAdvisory(`SCOPE_ROOT_ESCAPE: attempted target ${JSON.stringify(sanitizeDiagnosticText(filePath))} leaves active root ${JSON.stringify(sanitizeDiagnosticText(directory))}; ${safeRetry}. ACTION[architect]: verify the active lane root, redeclare only the exact relative path with replace_existing=true, and dispatch a new Task call.`,session,injectAdvisory,swarmState)}if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path247.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path247.resolve(dir,scope);return isPathIdentityWithin(resolvedFile,resolvedScope)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}var _internals190={sanitizePath,resolveWriteTargets:resolveWriteTargets2,resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBinding,resolveAuthorizedScopeBindingForSession,getAuthorizedPrFeedbackScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk,validatePrFeedbackScopeBinding,resolveSessionWorkspaceDirectory,describeScopeWorkspaceMismatch,resolveTaskId:(session)=>session?.currentTaskId??null};function denyWithArchitectAdvisory(message,session,injectAdvisory,state){if(session)session.lastScopeViolation=message,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[architectSessionId,architectSession]of state.agentSessions){let role=state.activeAgent.get(architectSessionId)??architectSession.agentName;if(stripKnownSwarmPrefix(role)!==ORCHESTRATOR_NAME)continue;try{injectAdvisory(architectSessionId,`[SCOPE GUARD] ${message}`)}catch{}break}throw Error(message)}function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let taskLabel2=taskId??"unknown",safeAgentName=sanitizeDiagnosticText(agentName,128),safeFilePath=sanitizeDiagnosticText(filePath,256),safeScope=scopeEntries.slice(0,3).map((entry)=>sanitizeDiagnosticText(entry,128)).join(", "),violationMessage=`SCOPE_VIOLATION: SCOPE VIOLATION: ${safeAgentName} attempted to modify '${safeFilePath}' which is not in declared scope for task ${taskLabel2}. Declared scope: [${safeScope}${scopeEntries.length>3?"...":""}]. Coder: correct a mistaken target; otherwise stop and ask the architect to expand declare_scope and dispatch a new Task call.`;denyWithArchitectAdvisory(violationMessage,session,injectAdvisory,state)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
|
|
6483
6484
|
`);try{injectAdvisory(sessionId,advisory)}catch{}}}}init_skill_propagation_gate();init_skill_scoring();init_skill_usage_log();import*as path248 from"node:path";var SKILL_INJECTION_THRESHOLD=0.5,SKILL_INJECTION_TOP_N=5;function injectSkillsIntoDelegation(directory,args2,recommendedSkills,targetAgent,sessionID,options={}){if(!recommendedSkills||recommendedSkills.length===0)return{injected:!1,injectedSkills:[]};let promptRaw=args2.prompt;if(typeof promptRaw!=="string")return{injected:!1,injectedSkills:[]};let parsedDelegation=parseDelegationArgs(args2);if(!parsedDelegation)return{injected:!1,injectedSkills:[]};if(parsedDelegation.skillsField.trim())return{injected:!1,injectedSkills:[]};let qualified=recommendedSkills.filter((s)=>s.score>=SKILL_INJECTION_THRESHOLD);if(qualified.length===0){if(args2.prompt=`SKILLS: none
|
|
6484
6485
|
|
|
6485
6486
|
${promptRaw}`,!options.quiet)console.warn("[skill-propagation-gate] No skills above threshold 0.5 — injected SKILLS: none");try{writeWarnEvent(directory,{type:"skill_injection_decision",timestamp:new Date().toISOString(),decision:"none",target_agent:targetAgent,sessionID,reason:"no_skill_above_threshold",threshold:SKILL_INJECTION_THRESHOLD,considered:recommendedSkills.map((s)=>({skillPath:s.skillPath,score:s.score}))})}catch{}return{injected:!0,injectedSkills:[]}}let topSkills=qualified.slice(0,SKILL_INJECTION_TOP_N),newPrompt=`${`SKILLS: ${topSkills.map((s)=>{let desc=readSkillMetadata(s.skillPath,directory).description||"";if(!desc||desc==="No description provided")desc=path248.basename(path248.dirname(s.skillPath));return desc=desc.replace(/,/g,";"),`file:${s.skillPath} (-- ${desc})`}).join(", ")}`}
|
|
@@ -6535,7 +6536,7 @@ When all tasks are complete, signal completion.`}async _withStateLock(fn2){let c
|
|
|
6535
6536
|
`,"utf8")}catch{}}async function removeCheckoutRestoreReceipt(receiptPath){await fsp7.rm(receiptPath)}async function restorePrWorkflowCheckout(directory,rawSessionID,requestedStashOid){let sessionID=normalizeSessionID3(rawSessionID);try{return await withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,async()=>{let receipts=await listCheckoutReceiptPaths(directory,sessionID);if(receipts.length===0)return{kind:"already_restored"};let normalizedRequested=requestedStashOid?.toLowerCase();if(normalizedRequested&&receipts.filter((entry)=>entry.stashOid===normalizedRequested).length!==1){let available=receipts.slice(0,MAX_CHECKOUT_RECEIPTS).map((entry)=>entry.stashOid);throw new CheckoutRestoreError("CHECKOUT_RESTORE_RECEIPT_AMBIGUOUS",`BLOCKED: no unique checkout receipt exists for stash ${normalizedRequested}; available stash_oid values: ${available.join(", ")}`)}let targets=await Promise.all(receipts.map(async(target)=>({...target,receipt:await readCheckoutRestoreReceipt(directory,target.receiptPath,sessionID,target.stashOid)})));targets.sort((left,right)=>left.receipt.preparedAt.localeCompare(right.receipt.preparedAt)||left.stashOid.localeCompare(right.stashOid));let verifiedCleanup=targets.filter((entry)=>entry.receipt.restoreState==="applied"&&typeof entry.receipt.restoreVerifiedAt==="string"),restoreTargets=targets.filter((entry)=>entry.receipt.restoreState!=="applied"||typeof entry.receipt.restoreVerifiedAt!=="string"),applied=restoreTargets.filter((entry)=>entry.receipt.restoreState==="applied"),pending=restoreTargets.filter((entry)=>entry.receipt.restoreState!=="applied"),observedStashes=null;try{observedStashes=await readCurrentStashOids(directory)}catch{}let receiptCleanupPending=!1;for(let target of verifiedCleanup)try{await _internals194.removeCheckoutRestoreReceipt(target.receiptPath)}catch{receiptCleanupPending=!0}if(restoreTargets.length===0){let first2=verifiedCleanup[0].receipt;return{kind:"restored",stashOids:targets.map((entry)=>entry.stashOid),retainedStashOids:observedStashes?targets.filter((entry)=>observedStashes.has(entry.stashOid)).map((entry)=>entry.stashOid):[],stashRetentionVerified:observedStashes!==null,originalHead:first2.originalHead,originalBranch:first2.originalBranch,restoredHead:first2.restoredHead,receiptCleanupPending}}let pendingDestinations=await Promise.all(pending.map((entry)=>resolveRestoreDestination(directory,entry.receipt))),destinations=[...applied.map((entry)=>({head:entry.receipt.restoredHead,branch:entry.receipt.restoredBranch})),...pendingDestinations],destination=destinations[0];if(destinations.some((candidate2)=>!sameRestoreDestination(destination,candidate2)))throw new CheckoutRestoreError("CHECKOUT_RESTORE_DESTINATION_AMBIGUOUS","BLOCKED: checkout receipts target different original checkouts; no switch or stash apply was attempted");if(pending.length>0){let activeStashes=observedStashes??await readCurrentStashOids(directory),missing=pending.filter((entry)=>!activeStashes.has(entry.stashOid));if(missing.length>0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_STASH_MISSING",`BLOCKED: ${missing.length} preserved checkout stash(es) are missing; no checkout mutation was attempted`)}if(applied.length>0){let currentIdentity;try{currentIdentity=await captureCheckoutIdentity(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: an applied checkout restoration could not be verified; its durable receipt remains for retry or manual recovery")}if(currentIdentity.originalHead!==destination.head||currentIdentity.originalBranch!==destination.branch)throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: an applied checkout restoration no longer matches its recorded destination; its durable receipt remains for manual recovery")}else if(applied.length===0){let status;try{status=await readPorcelainStatus(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_STATUS_FAILED","BLOCKED: unable to verify a clean destination checkout; no restore was attempted")}if(status.dirtyTrackedPaths.length>0||status.untrackedPaths.length>0||status.renameOrCopy)throw new CheckoutRestoreError("CHECKOUT_RESTORE_NOT_CLEAN","BLOCKED: checkout restoration requires a clean destination working tree; no switch or stash apply was attempted");if((await _internals194.runGit(directory,destination.branch?["switch","--",destination.branch]:["switch","--detach",destination.head])).exitCode!==0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_SWITCH_FAILED","BLOCKED: Git could not return to the recorded original checkout; the stash and receipt remain intact")}for(let target of pending){if((await _internals194.runGit(directory,["stash","apply","--index",target.stashOid])).exitCode!==0)throw new CheckoutRestoreError("CHECKOUT_RESTORE_APPLY_FAILED",`BLOCKED: Git could not reapply preserved stash ${target.stashOid}; its receipt and immutable stash remain for explicit manual recovery`);let appliedReceipt;try{appliedReceipt=await markReceiptApplied(directory,target.receiptPath,target.receipt,destination)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_APPLIED_STATE_WRITE_FAILED",`BLOCKED: preserved stash ${target.stashOid} was applied, but durable applied-state recording failed; inspect the working tree and retained stash manually`)}target.receipt=appliedReceipt}let restoredIdentity;try{restoredIdentity=await captureCheckoutIdentity(directory)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: checkout restoration completed but its final identity could not be verified; inspect the working tree and retained applied-state receipts manually")}if(restoredIdentity.originalHead!==destination.head||restoredIdentity.originalBranch!==destination.branch)throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFY_FAILED","BLOCKED: checkout restoration completed but its final identity could not be verified; inspect the working tree and retained applied-state receipts manually");for(let target of restoreTargets){if(!target.receipt.restoreVerifiedAt)try{target.receipt=await markReceiptVerified(directory,target.receiptPath,target.receipt)}catch{throw new CheckoutRestoreError("CHECKOUT_RESTORE_VERIFIED_STATE_WRITE_FAILED","BLOCKED: checkout restoration was verified, but durable verified-state recording failed; retained applied-state receipts remain for retry")}await appendRestoreEvent(directory,sessionID,target.receipt);try{await _internals194.removeCheckoutRestoreReceipt(target.receiptPath)}catch{receiptCleanupPending=!0}}let finalStashes=null;try{finalStashes=await readCurrentStashOids(directory)}catch{}let first=restoreTargets[0].receipt;return{kind:"restored",stashOids:targets.map((entry)=>entry.stashOid),retainedStashOids:finalStashes?targets.filter((entry)=>finalStashes.has(entry.stashOid)).map((entry)=>entry.stashOid):[],stashRetentionVerified:finalStashes!==null,originalHead:first.originalHead,originalBranch:first.originalBranch,restoredHead:destination.head,receiptCleanupPending}})}catch(error93){if(error93 instanceof Error&&error93.message.includes("checkout restoration is allowed only after"))throw new CheckoutRestoreError("CHECKOUT_RESTORE_GATE_ACTIVE",error93.message);if(error93 instanceof Error&&error93.message.includes("checkout restoration cannot mutate this project while session"))throw new CheckoutRestoreError("CHECKOUT_RESTORE_OTHER_SESSION_ACTIVE",error93.message);throw error93}}async function listPendingPrWorkflowCheckoutRestores(directory,sessionID){let receipts=await listCheckoutReceiptPaths(directory,normalizeSessionID3(sessionID));if(receipts.length===0)return[];let activeStashes=null;try{activeStashes=await readCurrentStashOids(directory)}catch{}return receipts.map((receipt)=>({stash_oid:receipt.stashOid,stash_present:activeStashes?.has(receipt.stashOid)??null}))}async function writeReceipt(directory,sessionID,preparation){let receiptPath=validateSwarmPath(directory,path254.join(RECEIPT_DIR,prWorkflowSessionFileStem(sessionID),`${preparation.stashOid}.json`));assertReceiptWithinByteBudget(sessionID,preparation),await writePrWorkflowAtomicJson(directory,receiptPath,buildReceiptDocument(sessionID,preparation))}async function appendPreparationEvent(directory,sessionID,preparation){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp7.appendFile(eventsPath,`${JSON.stringify({type:"pr_workflow_checkout_prepared",timestamp:preparation.preparedAt,sessionID,mode:preparation.mode,gateRevision:preparation.gateRevision,stashOid:preparation.stashOid,paths:preparation.paths})}
|
|
6536
6537
|
`,"utf-8")}catch{}}var _internals194={runGit:runGit7,readBoundedGitStdout,classifyGitState:classifyPrWorkflowGitState,removeCheckoutRestoreReceipt};function boundUntrustedPath(value){let cleaned="";for(let ch of value){let code=ch.codePointAt(0)??0,strip=code<=31||code>=127&&code<=159||code>=8234&&code<=8238||code>=8294&&code<=8297||ch==="`"||ch==="<"||ch===">";cleaned+=strip?" ":ch}return cleaned=cleaned.replace(/\s+/g," ").trim(),cleaned.length>MAX_ECHOED_PATH_LEN?`${cleaned.slice(0,MAX_ECHOED_PATH_LEN)}…`:cleaned}function structuredRestoreInstruction(stashOid){return`After complete_pr_workflow or abort_pr_workflow clears the gate, call prepare_pr_workflow_checkout with operation=restore; stash_oid=${stashOid} may be supplied as an exact receipt assertion`}function manualRecoveryInstruction(stashOid){return`manual recovery required: git stash apply --index ${stashOid}`}var prepare_pr_workflow_checkout=createSwarmTool({description:"Prepare or restore an auditable PR workflow checkout. Before binding, operation=prepare (the default) preserves dirty working-tree changes, records the original branch/HEAD and exact stash OID, and refuses unsafe state. After complete_pr_workflow or abort_pr_workflow clears the gate, one operation=restore call returns to the common recorded checkout and reapplies every pending receipt by immutable stash OID under the checkout mutation lock. Restored stashes remain as explicit safety backups because Git exposes no atomic identity-bound deletion for a non-top stash; the response lists retained_stash_oids. A PR_FEEDBACK branch may advance only as a descendant of its recorded commit; PR_REVIEW and detached identities remain exact. Legacy receipts derive the original commit from the stash and use a uniquely matching local branch when available. It refuses dirty, missing-stash, cross-session, divergent, or mixed-destination state without reset/clean. stash_oid is an optional exact receipt assertion, not a selector that leaves other receipts stranded. This tool never permits arbitrary stash commands.",args:{operation:PreparePrWorkflowCheckoutArgsSchema.shape.operation,paths:PreparePrWorkflowCheckoutArgsSchema.shape.paths,stash_oid:PreparePrWorkflowCheckoutArgsSchema.shape.stash_oid},execute:executePreparePrWorkflowCheckout});var AbortPrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).optional(),kind:exports_external.literal("recovery"),reason:exports_external.string().trim().min(1).max(500)}).strict();async function executeAbortPrWorkflow(args2,directory,context={}){let parsed=AbortPrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow abort: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow abort requires an active sessionID"});try{let summary=await abortPrWorkflow(directory,context.sessionID,{kind:parsed.data.kind,reason:parsed.data.reason,...parsed.data.mode?{expectedMode:parsed.data.mode}:{}}),checkoutRestoreRequired=!0,checkoutRestoreReceipts=[];try{checkoutRestoreReceipts=await listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{}return JSON.stringify({success:!0,mode:summary.mode,...summary.prHeadSha?{pr_head_sha:summary.prHeadSha}:{},open_lanes:summary.openLanes,...summary.presumedStaleLanes?.length?{presumed_stale_lanes:summary.presumedStaleLanes,presumed_stale_disclosure:summary.presumedStaleDisclosure}:{},...summary.probeDegradedReason?{probe_status:summary.probeDegradedReason}:{},...summary.stateSalvaged?{state_salvaged:!0,state_salvage_disclosure:summary.stateSalvageDisclosure}:{},...summary.casEscapeDisclosure?{cas_escape_disclosure:summary.casEscapeDisclosure}:{},gate_cleared:!0,checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var abort_pr_workflow=createSwarmTool({description:'Abort an active PR_REVIEW or PR_FEEDBACK mechanical gate and clear its durable session state, stopping the auto-resume loop. Requires kind: "recovery" and a one-line `reason`. Use after bounded recovery is exhausted, including a bound review or feedback workflow; do NOT use as a shortcut while useful recovery work remains. Refuses to abort while the workflow is armed for publication (call complete_pr_workflow instead) or while PR workflow lanes are still in flight (collect their results first). A lane past the staleness horizon whose session a liveness probe still reports as running also refuses the abort, and only the human-only /swarm abort-pr-workflow force path can override that retention; probe_status reports when a lane was instead settled without re-verification because the probe itself could not run. Reports checkout_restore_required when preserved pre-workflow changes remain. Reports state_salvaged with state_salvage_disclosure when the durable gate state was schema-invalid and had to be salvaged to clear it, and cas_escape_disclosure when the state revision was unsalvageable and the gate was therefore cleared without its compare-and-swap guard — treat either as a signal to re-verify the workflow before proceeding. Records a best-effort audit event to .swarm/events.jsonl.',args:{mode:AbortPrWorkflowArgsSchema.shape.mode,kind:AbortPrWorkflowArgsSchema.shape.kind,reason:AbortPrWorkflowArgsSchema.shape.reason},execute:executeAbortPrWorkflow});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs144 from"node:fs";import*as path255 from"node:path";var ACTIONLINT_TIMEOUT_MS=15000,ACTIONLINT_MAX_STDOUT_BYTES=4194304,ACTIONLINT_MAX_STDERR_BYTES=131072,DEFAULT_MAX_RESULTS=200,HARD_CAP_RESULTS=2000,MAX_WORKFLOW_FILES=500,MAX_WORKFLOW_DIRS=200,MAX_WORKFLOW_DEPTH=20;function resolveActionlintBinary(){return _internals195.resolveExecutableFromPath(["actionlint"])}function normalizeRelativeWorkflowFile(file3,workspace){if(!file3||containsControlChars(file3)||containsPathTraversal(file3))return null;if(path255.isAbsolute(file3)||/^[A-Za-z]:[/\\]/.test(file3))return null;let normalizedInput=file3.split(/[\\/]+/).filter(Boolean).join(path255.sep);if(!/\.(ya?ml)$/i.test(normalizedInput))return null;try{let realWorkspace=fs144.realpathSync(workspace),resolved=path255.resolve(realWorkspace,normalizedInput),realFile=fs144.realpathSync(resolved),relative60=path255.relative(realWorkspace,realFile);if(!relative60||relative60.startsWith("..")||path255.isAbsolute(relative60))return null;return relative60.split(path255.sep).join("/")}catch{return null}}function discoverWorkflowFiles(workspace){let root=path255.join(workspace,".github","workflows");if(!fs144.existsSync(root))return{files:[],truncated:!1};let files=[],dirCount=0,truncated=!1,visit=(dir,depth=0)=>{if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS||depth>MAX_WORKFLOW_DEPTH){truncated=!0;return}dirCount++;let entries;try{entries=fs144.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(files.length>=MAX_WORKFLOW_FILES||dirCount>=MAX_WORKFLOW_DIRS){truncated=!0;break}let full=path255.join(dir,entry.name);if(entry.isDirectory())visit(full,depth+1);else if(entry.isFile()&&/\.(ya?ml)$/i.test(entry.name)){let rel=normalizeRelativeWorkflowFile(path255.relative(workspace,full),workspace);if(rel)files.push(rel)}}};return visit(root),{files,truncated}}function parseActionlintOutput(stdout,workspace,maxResults){let findings=[],total=0;for(let line of stdout.split(`
|
|
6537
6538
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),file3=typeof entry.filepath==="string"?normalizeRelativeWorkflowFile(path255.isAbsolute(entry.filepath)?path255.relative(workspace,entry.filepath):entry.filepath,workspace):null;if(!file3)continue;if(total++,findings.length>=maxResults)continue;findings.push({file:file3,line:typeof entry.line==="number"?entry.line:1,column:typeof entry.column==="number"?entry.column:1,kind:typeof entry.kind==="string"?entry.kind:"unknown",message:typeof entry.message==="string"?entry.message:"",endColumn:typeof entry.end_column==="number"?entry.end_column:void 0})}catch{}}return{findings,total}}function sanitizeMaxResults(value){let numeric=typeof value==="number"&&Number.isFinite(value)?value:DEFAULT_MAX_RESULTS;return Math.min(Math.max(0,numeric),HARD_CAP_RESULTS)}var actionlint_scan=createSwarmTool({description:"Run actionlint against GitHub Actions workflow YAML files and return structured findings. Read-only; resolves actionlint lazily.",args:{files:exports_external.array(exports_external.string()).optional().describe("Optional workspace-relative workflow YAML files. Defaults to .github/workflows/**/*.yml,yaml."),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS).describe("Maximum findings to return")},execute:async(args2,directory)=>{let obj=typeof args2==="object"&&args2!==null?args2:{},maxResults=sanitizeMaxResults(obj.max_results),requestedFiles=Array.isArray(obj.files)?obj.files:void 0;if(requestedFiles?.some((f)=>typeof f!=="string"))return JSON.stringify({error:!0,type:"invalid-input",message:"files must be an array of strings"},null,2);let discovery=requestedFiles?{files:requestedFiles.map((f)=>normalizeRelativeWorkflowFile(f,directory)).filter((f)=>Boolean(f)),truncated:!1}:_internals195.discoverWorkflowFiles(directory),files=discovery.files;if(requestedFiles&&files.length!==requestedFiles.length)return JSON.stringify({error:!0,type:"path-escape",message:"files must be existing workspace-relative GitHub Actions YAML files"},null,2);let uniqueFiles=Array.from(new Set(files)),cappedFiles=uniqueFiles.slice(0,MAX_WORKFLOW_FILES),discoveryTruncated=discovery.truncated||uniqueFiles.length>cappedFiles.length;if(files=cappedFiles,files.length===0)return JSON.stringify({clean:!discoveryTruncated,findings:[],total:0,truncated:discoveryTruncated,files:[],command:["actionlint","-format","{{json .}}"],note:discoveryTruncated?`Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.`:"No GitHub Actions workflow YAML files found"},null,2);let executable=_internals195.resolveActionlintBinary();if(!executable)return JSON.stringify({error:!0,type:"actionlint-not-found",message:"actionlint executable not found. Install actionlint and ensure it is on PATH."},null,2);let lintArgs=["-format","{{json .}}",...files.map((file3)=>`./${file3}`)],run=await _internals195.runExternalTool({executable,args:lintArgs,cwd:directory,timeoutMs:ACTIONLINT_TIMEOUT_MS,maxStdoutBytes:ACTIONLINT_MAX_STDOUT_BYTES,maxStderrBytes:ACTIONLINT_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`actionlint timed out after ${ACTIONLINT_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"actionlint failed to start"},null,2);let{findings,total}=parseActionlintOutput(run.stdout,directory,maxResults);if(run.exitCode!==0&&findings.length===0&&run.stderr)return JSON.stringify({error:!0,type:"unknown",message:run.stderr.split(`
|
|
6538
|
-
`)[0]},null,2);return JSON.stringify({findings,total,truncated:discoveryTruncated||total>maxResults||run.stdoutTruncated||run.stderrTruncated,files,command:["actionlint",...lintArgs],outputTruncated:run.stdoutTruncated||run.stderrTruncated,clean:findings.length===0&&total===0&&!discoveryTruncated&&!run.stdoutTruncated&&!run.stderrTruncated,note:discoveryTruncated?`Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.`:void 0},null,2)}}),_internals195={resolveExecutableFromPath,resolveActionlintBinary,runExternalTool,discoverWorkflowFiles,parseActionlintOutput};init_zod();init_config();import{existsSync as
|
|
6539
|
+
`)[0]},null,2);return JSON.stringify({findings,total,truncated:discoveryTruncated||total>maxResults||run.stdoutTruncated||run.stderrTruncated,files,command:["actionlint",...lintArgs],outputTruncated:run.stdoutTruncated||run.stderrTruncated,clean:findings.length===0&&total===0&&!discoveryTruncated&&!run.stdoutTruncated&&!run.stderrTruncated,note:discoveryTruncated?`Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.`:void 0},null,2)}}),_internals195={resolveExecutableFromPath,resolveActionlintBinary,runExternalTool,discoverWorkflowFiles,parseActionlintOutput};init_zod();init_config();import{existsSync as existsSync132,mkdirSync as mkdirSync66,mkdtempSync as mkdtempSync4,readFileSync as readFileSync98,realpathSync as realpathSync41,renameSync as renameSync36,rmdirSync as rmdirSync2,unlinkSync as unlinkSync35,writeFileSync as writeFileSync42}from"node:fs";import*as path256 from"node:path";class SequenceMatcher{a;b;isJunk;autoJunk;b2j=new Map;popularSet=new Set;matchingBlocks=null;constructor(isJunk,a,b,autoJunk=!0){this.a=a,this.b=b,this.isJunk=isJunk,this.autoJunk=autoJunk,this.chainB()}setSeqs(a,b){this.a=a,this.b=b,this.matchingBlocks=null,this.chainB()}chainB(){let b=this.b,b2j=new Map;for(let i=0;i<b.length;i++){let ch=b[i],positions=b2j.get(ch);if(positions===void 0)b2j.set(ch,[i]);else positions.push(i)}if(this.isJunk){let junk=[];for(let ch of b2j.keys())if(this.isJunk(ch))junk.push(ch);for(let ch of junk)b2j.delete(ch)}if(this.popularSet=new Set,this.autoJunk&&b.length>=200){let threshold=b.length*0.01+0.5,popular=[];for(let[ch,indices]of b2j)if(indices.length>threshold)popular.push(ch);for(let ch of popular)this.popularSet.add(ch),b2j.delete(ch)}this.b2j=b2j}findLongestMatch(alo,ahi,blo,bhi){let a=this.a,b=this.b,b2j=this.b2j,bestI=alo,bestJ=blo,bestSize=0,j2len=new Map;for(let i=alo;i<ahi;i++){let ch=a[i],positions=b2j.get(ch);if(positions===void 0){j2len.clear();continue}let newJ2len=new Map;for(let j of positions){if(j<blo)continue;if(j>=bhi)break;let size=(j2len.get(j-1)??0)+1;if(newJ2len.set(j,size),size>bestSize)bestI=i-size+1,bestJ=j-size+1,bestSize=size}j2len.clear();for(let[k,v]of newJ2len)j2len.set(k,v)}while(bestI>alo&&bestJ>blo&&a[bestI-1]===b[bestJ-1])bestI--,bestJ--,bestSize++;while(bestI+bestSize<ahi&&bestJ+bestSize<bhi&&a[bestI+bestSize]===b[bestJ+bestSize])bestSize++;return{a:bestI,b:bestJ,size:bestSize}}getMatchingBlocks(){if(this.matchingBlocks!==null)return this.matchingBlocks;let la=this.a.length,lb=this.b.length,matches=[],stack=[[0,la,0,lb]];while(stack.length>0){let[alo,ahi,blo,bhi]=stack.pop(),m=this.findLongestMatch(alo,ahi,blo,bhi),{a:i,b:j,size}=m;if(size>0){if(matches.push(m),alo<i&&blo<j)stack.push([alo,i,blo,j]);if(i+size<ahi&&j+size<bhi)stack.push([i+size,ahi,j+size,bhi])}}return matches.sort((x,y)=>x.a-y.a||x.b-y.b),matches.push({a:la,b:lb,size:0}),this.matchingBlocks=matches,matches}ratio(){let matches=this.getMatchingBlocks(),m=0;for(let block of matches)m+=block.size;let t=this.a.length+this.b.length;if(t===0)return 1;return 2*m/t}getOpcodes(){let blocks=this.getMatchingBlocks(),opcodes=[],i=0,j=0;for(let block of blocks){let{a:ai,b:bj,size}=block;if(i<ai&&j<bj)opcodes.push({tag:"replace",i1:i,i2:ai,j1:j,j2:bj});else if(i<ai)opcodes.push({tag:"delete",i1:i,i2:ai,j1:j,j2:bj});else if(j<bj)opcodes.push({tag:"insert",i1:i,i2:ai,j1:j,j2:bj});if(size>0)opcodes.push({tag:"equal",i1:ai,i2:ai+size,j1:bj,j2:bj+size});i=ai+size,j=bj+size}return opcodes}}var UNICODE_MAP={"“":'"',"”":'"',"‘":"'","’":"'","—":"--","–":"-","…":"..."," ":" "};function unicodeNormalize(text){let out=text;for(let[char,repl]of Object.entries(UNICODE_MAP))out=out.split(char).join(repl);return out}function leadingWhitespace(line){let i=0;while(i<line.length&&(line[i]===" "||line[i]==="\t"))i++;return line.slice(0,i)}function firstMeaningfulLine(text){for(let line of text.split(`
|
|
6539
6540
|
`))if(line.trim())return line;return null}function fuzzyFindAndReplace(content,oldString,newString,replaceAll=!1,options={}){if(!oldString)return{content,matchCount:0,strategy:null,error:"old_string cannot be empty"};if(oldString===newString)return{content,matchCount:0,strategy:null,error:"old_string and new_string are identical"};let strategies=[["exact",strategyExact],["line_trimmed",strategyLineTrimmed],["whitespace_normalized",strategyWhitespaceNormalized],["indentation_flexible",strategyIndentationFlexible],["escape_normalized",strategyEscapeNormalized],["trimmed_boundary",strategyTrimmedBoundary],["unicode_normalized",strategyUnicodeNormalized],["block_anchor",strategyBlockAnchor]];if(options.includeContextAware!==!1)strategies.push(["context_aware",strategyContextAware]);for(let[strategyName,strategyFn]of strategies){let matches=strategyFn(content,oldString);if(matches.length===0)continue;if(matches.length>1&&!replaceAll)return{content,matchCount:0,strategy:null,error:`Found ${matches.length} matches for old_string. Provide more context to make it unique, or use replace_all=true.`};if(strategyName!=="exact"){let driftErr=detectEscapeDrift(content,matches,oldString,newString);if(driftErr)return{content,matchCount:0,strategy:null,error:driftErr}}let effectiveNew=maybeUnescapeNewString(newString,content,matches);if(strategyName==="unicode_normalized"||strategyName==="block_anchor"||strategyName==="context_aware")effectiveNew=preserveUnicodeInReplacement(content,matches,oldString,effectiveNew);return{content:applyReplacements(content,matches,effectiveNew,strategyName!=="exact"?oldString:null),matchCount:matches.length,strategy:strategyName,error:null}}return{content,matchCount:0,strategy:null,error:"Could not find a match for old_string in the file"}}function detectEscapeDrift(content,matches,oldString,newString){if(!newString.includes("\\'")&&!newString.includes("\\\""))return null;let matchedRegions="";for(let[start,end]of matches)matchedRegions+=content.slice(start,end);for(let suspect of["\\'","\\\""])if(newString.includes(suspect)&&oldString.includes(suspect)&&!matchedRegions.includes(suspect)){let plain=suspect[1];return`Escape-drift detected: old_string and new_string contain the literal sequence ${JSON.stringify(suspect)} but the matched region of the file does not. This is almost always a tool-call serialization artifact where an apostrophe or quote got prefixed with a spurious backslash. Re-read the file with read_file and pass old_string/new_string without backslash-escaping ${JSON.stringify(plain)} characters.`}return null}function maybeUnescapeNewString(newString,content,matches){if(!newString.includes("\\t")&&!newString.includes("\\r"))return newString;let matchedRegions="";for(let[start,end]of matches)matchedRegions+=content.slice(start,end);let out=newString;if(out.includes("\\t")&&matchedRegions.includes("\t"))out=out.split("\\t").join("\t");if(out.includes("\\r")&&matchedRegions.includes("\r"))out=out.split("\\r").join("\r");return out}function reindentReplacement(fileRegion,oldString,newString){if(!newString)return newString;let oldFirst=firstMeaningfulLine(oldString),fileFirst=firstMeaningfulLine(fileRegion);if(oldFirst===null||fileFirst===null)return newString;let oldIndent=leadingWhitespace(oldFirst),fileIndent=leadingWhitespace(fileFirst);if(oldIndent===fileIndent)return newString;let outLines=[];for(let line of newString.split(`
|
|
6540
6541
|
`)){if(!line.trim()){outLines.push(line);continue}if(leadingWhitespace(line).startsWith(oldIndent)){let remainder=line.slice(oldIndent.length);outLines.push(fileIndent+remainder)}else outLines.push(fileIndent+line.replace(/^[ \t]+/,""))}return outLines.join(`
|
|
6541
6542
|
`)}function preserveUnicodeInReplacement(content,matches,oldString,newString){let fileRegion="";for(let[start,end]of matches)fileRegion+=content.slice(start,end);let normOld=unicodeNormalize(oldString),normFile=unicodeNormalize(fileRegion);if(normOld!==normFile)return newString;let fileOrigToNorm=buildOrigToNormMap(fileRegion),fileNormToOrig=new Map;for(let origPos=0;origPos<fileOrigToNorm.length-1;origPos++){let np=fileOrigToNorm[origPos];if(!fileNormToOrig.has(np))fileNormToOrig.set(np,origPos)}let opcodes=new SequenceMatcher(null,normOld,newString).getOpcodes(),resultParts=[];for(let op of opcodes){let{tag,i1,i2,j1,j2}=op;if(tag==="equal"){let origStart=fileNormToOrig.get(i1)??0,origEnd=origStart;while(origEnd<fileRegion.length&&fileOrigToNorm[origEnd]<i2)origEnd++;resultParts.push(fileRegion.slice(origStart,origEnd))}else if(tag==="replace")resultParts.push(newString.slice(j1,j2));else if(tag==="delete");else if(tag==="insert")resultParts.push(newString.slice(j1,j2))}return resultParts.join("")}function applyReplacements(content,matches,newString,oldString){let sorted=[...matches].sort((x,y)=>y[0]-x[0]),result=content;for(let[start,end]of sorted){let adjusted=oldString!==null?reindentReplacement(content.slice(start,end),oldString,newString):newString;result=result.slice(0,start)+adjusted+result.slice(end)}return result}function buildOrigToNormMap(original){let result=[],normPos=0;for(let i=0;i<original.length;i++){result.push(normPos);let repl=UNICODE_MAP[original[i]];normPos+=repl!==void 0?repl.length:1}return result.push(normPos),result}function mapPositionsNormToOrig(origToNorm,normMatches){let normToOrigStart=new Map;for(let origPos=0;origPos<origToNorm.length-1;origPos++){let normPos=origToNorm[origPos];if(!normToOrigStart.has(normPos))normToOrigStart.set(normPos,origPos)}let results=[],origLen=origToNorm.length-1;for(let[normStart,normEnd]of normMatches){if(!normToOrigStart.has(normStart))continue;let origStart=normToOrigStart.get(normStart),origEnd=origStart;while(origEnd<origLen&&origToNorm[origEnd]<normEnd)origEnd++;results.push([origStart,origEnd])}return results}function calculateLinePositions(contentLines,startLine,endLine,contentLength){let start=0;for(let i=0;i<startLine;i++)start+=contentLines[i].length+1;let end=0;for(let i=0;i<endLine;i++)end+=contentLines[i].length+1;return end-=1,end=Math.min(contentLength,end),[start,end]}function findNormalizedMatches(content,contentLines,contentNormalizedLines,patternNormalized){let numPatternLines=patternNormalized.split(`
|
|
@@ -6570,34 +6571,34 @@ When all tasks are complete, signal completion.`}async _withStateLock(fn2){let c
|
|
|
6570
6571
|
`),fuzzy=fuzzyFindAndReplace(currentContent,oldString,newString,!1,{includeContextAware:options.fuzzyMatchContextAware});if(fuzzy.error===null&&fuzzy.matchCount===1){fileLines.length=0;for(let line of fuzzy.content.split(`
|
|
6571
6572
|
`))fileLines.push(line);accumulatedDelta+=newLinesForHunk.length-expectedOldLines.length;continue}fuzzyAttemptedThisHunk=!0}if(!matchFound){let diagStart=Math.min(searchStart,fileLines.length),diagEnd=Math.min(diagStart+expectedOldLines.length,fileLines.length),actualContent=fileLines.slice(diagStart,diagEnd).join(`
|
|
6572
6573
|
`),expectedContent=expectedOldLines.join(`
|
|
6573
|
-
`);return{success:!1,failedHunkIndex:hunkIdx,fuzzyAttempted:fuzzyAttemptedThisHunk?!0:void 0,error:{hunkIndex:hunkIdx,type:"context-mismatch",message:`Context mismatch in hunk ${hunkIdx+1} at line ${searchStart+1}: expected context does not match file content`,expected:expectedContent.length>200?`${expectedContent.slice(0,200)}... (truncated)`:expectedContent,actual:actualContent.length>200?`${actualContent.slice(0,200)}... (truncated)`:actualContent,line:searchStart+1}}}}return{success:!0,appliedLines:fileLines}}function atomicWriteFileSync3(targetPath,content){let dir=path256.dirname(targetPath);mkdirSync66(dir,{recursive:!0});let tempPrefix=`.apply-patch-${Date.now()}-${process.pid}`,tempPath;try{let tempDir=realpathSync41(mkdtempSync4(path256.join(dir,tempPrefix)));tempPath=path256.join(tempDir,"content")}catch{tempPath=path256.join(dir,`${tempPrefix}.tmp`)}try{writeFileSync42(tempPath,content,"utf-8"),renameSync36(tempPath,targetPath)}finally{if(
|
|
6574
|
+
`);return{success:!1,failedHunkIndex:hunkIdx,fuzzyAttempted:fuzzyAttemptedThisHunk?!0:void 0,error:{hunkIndex:hunkIdx,type:"context-mismatch",message:`Context mismatch in hunk ${hunkIdx+1} at line ${searchStart+1}: expected context does not match file content`,expected:expectedContent.length>200?`${expectedContent.slice(0,200)}... (truncated)`:expectedContent,actual:actualContent.length>200?`${actualContent.slice(0,200)}... (truncated)`:actualContent,line:searchStart+1}}}}return{success:!0,appliedLines:fileLines}}function atomicWriteFileSync3(targetPath,content){let dir=path256.dirname(targetPath);mkdirSync66(dir,{recursive:!0});let tempPrefix=`.apply-patch-${Date.now()}-${process.pid}`,tempPath;try{let tempDir=realpathSync41(mkdtempSync4(path256.join(dir,tempPrefix)));tempPath=path256.join(tempDir,"content")}catch{tempPath=path256.join(dir,`${tempPrefix}.tmp`)}try{writeFileSync42(tempPath,content,"utf-8"),renameSync36(tempPath,targetPath)}finally{if(existsSync132(tempPath))try{unlinkSync35(tempPath)}catch{}let tempDir=path256.dirname(tempPath);if(tempDir!==dir&&existsSync132(tempDir))try{rmdirSync2(tempDir)}catch{}}}function detectLineEnding(content){return content.includes(`\r
|
|
6574
6575
|
`)?`\r
|
|
6575
6576
|
`:`
|
|
6576
6577
|
`}function ensureFinalNewline(content,originalEndsWithNewline){if(originalEndsWithNewline&&!content.endsWith(`
|
|
6577
6578
|
`))return`${content}
|
|
6578
6579
|
`;if(!originalEndsWithNewline&&content.endsWith(`
|
|
6579
|
-
`))return content.slice(0,-1);return content}function processFileDiff(fileDiff,targetPath,fullPath,workspace,dryRun,allowCreates,allowDeletes,hunkOptions){let hunksTotal=fileDiff.hunks.length;if(!isCanonicalPathWithinWorkspace(fullPath,workspace))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"context-mismatch",message:`Path escapes workspace via symlink/junction: ${targetPath}`}]};if(isCanonicalProtectedPath(fullPath,workspace))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"context-mismatch",message:`Protected directory target rejected via symlink: ${targetPath}`}]};if(fileDiff.isNewFile){if(!allowCreates)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"create-not-allowed",message:`New file creation not allowed: ${targetPath} (set allowCreates to true)`}]};let parentDir=path256.dirname(fullPath);if(!
|
|
6580
|
-
`),!0);atomicWriteFileSync3(fullPath,content2)}return{file:targetPath,status:"created",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}if(fileDiff.isDelete){if(hunksTotal===0)return{file:targetPath,status:"no-changes",hunks:0,hunksApplied:0,hunksFailed:0};if(!allowDeletes)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"delete-not-allowed",message:`File deletion not allowed: ${targetPath} (set allowDeletes to true)`}]};if(!
|
|
6580
|
+
`))return content.slice(0,-1);return content}function processFileDiff(fileDiff,targetPath,fullPath,workspace,dryRun,allowCreates,allowDeletes,hunkOptions){let hunksTotal=fileDiff.hunks.length;if(!isCanonicalPathWithinWorkspace(fullPath,workspace))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"context-mismatch",message:`Path escapes workspace via symlink/junction: ${targetPath}`}]};if(isCanonicalProtectedPath(fullPath,workspace))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"context-mismatch",message:`Protected directory target rejected via symlink: ${targetPath}`}]};if(fileDiff.isNewFile){if(!allowCreates)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"create-not-allowed",message:`New file creation not allowed: ${targetPath} (set allowCreates to true)`}]};let parentDir=path256.dirname(fullPath);if(!existsSync132(parentDir))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`Parent directory does not exist: ${parentDir}`}]};if(existsSync132(fullPath))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`File already exists: ${targetPath} (cannot create — patch may be stale)`}]};if(hunksTotal===0)return{file:targetPath,status:"no-changes",hunks:0,hunksApplied:0,hunksFailed:0};let hunkResult2=applyHunks("",fileDiff);if(!hunkResult2.success||!hunkResult2.appliedLines)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:hunkResult2.error?[hunkResult2.error]:[]};if(!dryRun){let content2=ensureFinalNewline(hunkResult2.appliedLines.join(`
|
|
6581
|
+
`),!0);atomicWriteFileSync3(fullPath,content2)}return{file:targetPath,status:"created",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}if(fileDiff.isDelete){if(hunksTotal===0)return{file:targetPath,status:"no-changes",hunks:0,hunksApplied:0,hunksFailed:0};if(!allowDeletes)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"delete-not-allowed",message:`File deletion not allowed: ${targetPath} (set allowDeletes to true)`}]};if(!existsSync132(fullPath))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`File not found for deletion: ${targetPath}`}]};if(!dryRun)try{unlinkSync35(fullPath)}catch(err){return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`Failed to delete file: ${err instanceof Error?err.message:String(err)}`}]}}return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}if(!existsSync132(fullPath))return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`File not found: ${targetPath}`}]};let content;try{content=readFileSync98(fullPath,"utf-8")}catch(err){return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:[{hunkIndex:0,type:"file-not-found",message:`Could not read file: ${err instanceof Error?err.message:String(err)}`}]}}if(hunksTotal===0)return{file:targetPath,status:"no-changes",hunks:0,hunksApplied:0,hunksFailed:0};let originalEndsWithNewline=content.endsWith(`
|
|
6581
6582
|
`),originalLineEnding=detectLineEnding(content),hunkResult=applyHunks(content,fileDiff,hunkOptions);if(!hunkResult.success){let errors5=hunkResult.error?[hunkResult.error]:[];if(hunkResult.fuzzyAttempted&&errors5.length>0&&hunkOptions?.fuzzyMatch){let expectedAnchor=errors5[0].expected??"",hint=findClosestLines(expectedAnchor,content);if(hint)errors5=[{...errors5[0],message:`${errors5[0].message}
|
|
6582
6583
|
|
|
6583
6584
|
Did you mean one of these sections?
|
|
6584
6585
|
${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0,hunksFailed:hunksTotal,errors:errors5}}let resultContent=hunkResult.appliedLines.join(`
|
|
6585
6586
|
`);if(resultContent===""&&!dryRun&&!allowDeletes&&content.length>0)return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0,errors:[{hunkIndex:0,type:"delete-not-allowed",message:`Patch would delete all content from ${targetPath}. Set allowDeletes to true to permit file deletion.`}]};let finalContent;if(resultContent==="")finalContent="";else{let withLineEnding=originalLineEnding===`\r
|
|
6586
6587
|
`?resultContent.replace(/\n/g,`\r
|
|
6587
|
-
`):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync3(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch2=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Indented patches (e.g. inside a fenced markdown/YAML block) are automatically dedented to column 0 before parsing — the diff body itself may be indented. Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those. Accepts the payload as `patch` (canonical) or any of the aliases `patchText`, `patch_text`, `patchPayload` (#2206); the resolver picks the first non-empty one.",args:{patch:exports_external.string().optional().describe("Unified diff text to parse and apply (optional when an alias below carries the payload)"),patchText:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patch_text:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patchPayload:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=[obj.patch,obj.patchText,obj.patch_text,obj.patchPayload].find((value)=>typeof value==="string"&&value.length>0)??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1,{config:config3}=_internals196.loadPluginConfigWithMeta(directory),fuzzyMatch=config3.apply_patch?.fuzzy_match===!0,fuzzyMatchContextAware=config3.apply_patch?.fuzzy_match_context_aware===!0,hunkOptions=fuzzyMatch||fuzzyMatchContextAware?{fuzzyMatch,fuzzyMatchContextAware}:void 0;if(!
|
|
6588
|
+
`):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync3(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch2=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Indented patches (e.g. inside a fenced markdown/YAML block) are automatically dedented to column 0 before parsing — the diff body itself may be indented. Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those. Accepts the payload as `patch` (canonical) or any of the aliases `patchText`, `patch_text`, `patchPayload` (#2206); the resolver picks the first non-empty one.",args:{patch:exports_external.string().optional().describe("Unified diff text to parse and apply (optional when an alias below carries the payload)"),patchText:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patch_text:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patchPayload:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=[obj.patch,obj.patchText,obj.patch_text,obj.patchPayload].find((value)=>typeof value==="string"&&value.length>0)??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1,{config:config3}=_internals196.loadPluginConfigWithMeta(directory),fuzzyMatch=config3.apply_patch?.fuzzy_match===!0,fuzzyMatchContextAware=config3.apply_patch?.fuzzy_match_context_aware===!0,hunkOptions=fuzzyMatch||fuzzyMatchContextAware?{fuzzyMatch,fuzzyMatchContextAware}:void 0;if(!existsSync132(directory))return JSON.stringify(buildErrorResult("Workspace directory does not exist"),null,2);if(files.length===0)return JSON.stringify(buildErrorResult("files array cannot be empty"),null,2);if(!patchText||patchText.trim()==="")return JSON.stringify(buildErrorResult("patch text cannot be empty"),null,2);if(isUnsupportedPatchFormat(patchText))return JSON.stringify(buildErrorResult("Unsupported patch format: *** Begin Patch / *** Update File style payloads are not supported by swarm_apply_patch. Use the native apply_patch tool for this format, or provide a standard unified diff (--- a/file / +++ b/file / @@ hunks)."),null,2);for(let filePath of files){let validationError=validatePatchTargetPath(filePath,directory);if(validationError)return JSON.stringify(buildErrorResult(validationError),null,2)}let{files:parsedFiles,error:parseError}=parseUnifiedDiff(patchText);if(parseError)return JSON.stringify(buildErrorResult(parseError),null,2);if(parsedFiles.length===0)return JSON.stringify({success:!0,dryRun,files:[],summary:{totalFiles:0,applied:0,failed:0,totalHunks:0}},null,2);let declaredFileSet=new Set(files),undeclaredTargets=[];for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath;if(targetPath&&targetPath!=="/dev/null"&&!declaredFileSet.has(targetPath))undeclaredTargets.push(targetPath)}if(undeclaredTargets.length>0)return JSON.stringify(buildErrorResult(`Patch targets files not in the declared files array: ${undeclaredTargets.join(", ")}`),null,2);let parsedTargetSet=new Set(parsedFiles.map((fd)=>fd.isDelete?fd.oldPath:fd.newPath).filter(Boolean)),extraFiles=files.filter((f)=>!parsedTargetSet.has(f)),fileResults=[],totalApplied=0,totalFailed=0,totalHunks=0;for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath,fullPath=path256.resolve(directory,targetPath);totalHunks+=fileDiff.hunks.length;let result=processFileDiff(fileDiff,targetPath,fullPath,directory,dryRun,allowCreates,allowDeletes,hunkOptions);if(fileResults.push(result),result.status==="applied"||result.status==="created")totalApplied++;else if(result.status==="error")totalFailed++}let output={success:totalFailed===0,dryRun,files:fileResults,summary:{totalFiles:fileResults.length,applied:totalApplied,failed:totalFailed,totalHunks}};if(extraFiles.length>0)return JSON.stringify({...output,warnings:[`files[] contains entries not targeted by the patch: ${extraFiles.join(", ")}`]},null,2);return JSON.stringify(output,null,2)}});init_zod();init_delegation_gate();init_create_tool();var ApprovePlanCriticArgsSchema=exports_external.object({reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "critic returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApprovePlanCritic(args2,directory,context={}){let parsed=ApprovePlanCriticArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_plan_critic call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_plan_critic requires an active sessionID"});try{let summary=await forceRecordPlanCriticApproval(directory,context.sessionID,{reason:parsed.data.reason,userConfirmed:!1});return JSON.stringify({success:!0,plan_id:summary.planId,recorded_at:summary.recordedAt,method:"manual_override",user_confirmed:!1,message:"Recorded a manual plan_critic_gate approval snapshot. The critic_pre_plan execution gate will now allow coder delegation. An audit event was appended to .swarm/events.jsonl."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_plan_critic=createSwarmTool({description:'Record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race — issue #2012). The snapshot carries a distinct method: "manual_override" audit marker. Architect-only: the active session must be the architect. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost. A reason is required and audited to .swarm/events.jsonl. The human-confirmed variant is /swarm approve-plan-critic.',args:{reason:ApprovePlanCriticArgsSchema.shape.reason},execute:executeApprovePlanCritic});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs145 from"node:fs";import*as path257 from"node:path";var AST_GREP_TIMEOUT_MS=1e4,AST_GREP_MAX_STDOUT_BYTES=8388608,AST_GREP_MAX_STDERR_BYTES=65536,DEFAULT_MAX_RESULTS2=100,HARD_CAP_RESULTS2=1e4,MAX_PATTERN_LENGTH=20000;function splitGlobPatterns(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}function resolveAstGrepBinary(){return _internals197.resolveExecutableFromPath(["ast-grep","sg"])}function toWorkspaceRelativePath(filePath,workspace){try{let resolved=path257.resolve(workspace,filePath),realWorkspace=fs145.realpathSync(workspace),realResolved=fs145.realpathSync(resolved),relative62=path257.relative(realWorkspace,realResolved);if(!relative62||relative62.startsWith("..")||path257.isAbsolute(relative62))return null;return relative62.split(path257.sep).join("/")}catch{return null}}function parseAstGrepStream(stdout,workspace,maxResults){let matches=[],total=0;for(let line of stdout.split(`
|
|
6588
6589
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs145.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals197.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals197.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
|
|
6589
6590
|
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals197={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_dist();init_create_tool();init_symbols();init_path_security();import*as fs146 from"node:fs";import*as path258 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path258.resolve(workspace,filePath);if(!fs146.existsSync(resolvedPath))return!0;let realWorkspace=fs146.realpathSync(workspace),realResolvedPath=fs146.realpathSync(resolvedPath),relativePath2=path258.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path258.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path258.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path258.join(cwd,file3);if(!fs146.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs146.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs146.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_manager2();init_bun_compat();init_logger();init_create_tool();var DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100;function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
6590
6591
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
6591
6592
|
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason;if(runs.length===0)if(verdict="info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason="No build commands discovered (no toolchains found)";else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs147 from"node:fs";import*as path259 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path259.resolve(workspaceRoot),swarmPath3=path259.join(normalizedWorkspace,".swarm","evidence");return path259.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs147.existsSync(evidencePath))return null;let content;try{content=fs147.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path259.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let requiredGates=evidenceData.required_gates||[],gatesMap=evidenceData.gates||{},passedGates=[],missingGates=[];for(let requiredGate of requiredGates)if(gatesMap[requiredGate])passedGates.push(requiredGate);else missingGates.push(requiredGate);let status=missingGates.length===0?"all_passed":"incomplete",message;if(status==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status==="all_passed")status="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80)}).strict();async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={};try{let settlement=await _internals198.settlePresumedStalePrWorkflowLanes(directory,context.sessionID);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason}catch{}let amendmentDisclosure={};try{let gateState=await _internals198.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let status=await _internals198.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status==="completed")try{checkoutRestoreReceipts=await _internals198.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status,ready_to_publish:status==="ready-to-publish",verified_no_change:status==="verified-no-change",gate_cleared:status==="completed"||status==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha},execute:executeCompletePrWorkflow}),_internals198={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs148 from"node:fs";import*as path260 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs148.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath2=filePath.replace(/\\/g,"/"),resolvedPath=path260.resolve(directory,normalizedPath2),projectRoot=path260.resolve(directory),relative64=path260.relative(projectRoot,resolvedPath);if(!(relative64===""||!relative64.startsWith("..")&&!path260.isAbsolute(relative64))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs148.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path260.join(directory,".swarm","evidence",`${phase}`),evidencePath=path260.join(evidenceDir,"completion-verify.json");fs148.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs148.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import*as fs149 from"node:fs";import*as path261 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals199={bunSpawn,resolveGitExecutable};async function getGitChurn(days,directory){let churnMap=new Map,proc=_internals199.bunSpawn([_internals199.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",cwd:directory}),[stdout]=await Promise.all([proc.stdout.text(),proc.exited]);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath2=line.replace(/\\/g,"/");if(!normalizedPath2||normalizedPath2.trim()==="")continue;if(normalizedPath2.includes("node_modules")||normalizedPath2.includes("/.git/")||normalizedPath2.includes("/dist/")||normalizedPath2.includes("/build/")||normalizedPath2.includes("__tests__"))continue;if(normalizedPath2.includes(".test.")||normalizedPath2.includes(".spec."))continue;churnMap.set(normalizedPath2,(churnMap.get(normalizedPath2)||0)+1)}return churnMap}function getComplexityForFile2(filePath){try{if(fs149.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs149.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path261.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs149.existsSync(fullPath))fullPath=path261.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store3();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store3();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals200.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected,failed,...error93?{error:error93}:{}}}var _internals200={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_state2();init_create_tool();var _internals201={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimit=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit),usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Report current context-window headroom for the active session. Returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",args:{},async execute(_args,directory,ctx){let config3=_internals201.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals201.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID});return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
6592
|
-
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();import{existsSync as existsSync136,mkdirSync as mkdirSync68,readFileSync as readFileSync103}from"node:fs";import{join as join207}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals202={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join207(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync68(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals202.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync136(filePath))try{let raw=readFileSync103(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync103(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_lock();init_task_file();import{createHash as createHash55,randomUUID as randomUUID30}from"node:crypto";import{closeSync as closeSync28,existsSync as existsSync137,fsyncSync as fsyncSync9,mkdirSync as mkdirSync69,openSync as openSync28,readFileSync as readFileSync104,readSync as readSync19,statSync as statSync57,writeSync as writeSync4}from"node:fs";import{dirname as dirname106,join as join208}from"node:path";var VERSION=1,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha2565(value){return createHash55("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");return`task-${sha2565(scope.taskId)}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");return`phase-${scope.phaseNumber}`}if(typeof scope.generation!=="string"||scope.generation.length===0||scope.generation.length>256)throw Error("invalid final council scope");return`final-${sha2565(scope.generation)}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha2565(scope.taskId)};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber};return{kind:"final",scopeHash:sha2565(scope.generation)}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join208(directory,".swarm","council","round-state",`${token}.json`),audit:join208(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join208("council","round-state",`${token}.json`)}}function canonicalize2(value){if(Array.isArray(value))return value.map(canonicalize2);if(value&&typeof value==="object"){let result=Object.create(null);for(let key of Object.keys(value).sort()){if(key==="working_directory"||key==="roundNumber"||key==="provenanceAgentName"||key==="provenanceSessionId")continue;result[key]=canonicalize2(value[key])}return result}return value}function councilRequestDigest(request,round){return sha2565(JSON.stringify({round,request:canonicalize2(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state=value;return state.version===VERSION&&isRound(state.currentRound)&&(state.status==="open"||state.status==="closed")&&typeof state.maxRoundsExhausted==="boolean"&&(state.lastAttemptId===void 0||isUuid2(state.lastAttemptId))&&(state.lastDigest===void 0||isDigest(state.lastDigest))&&state.lastAttemptId===void 0===(state.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2){let current=tail2.truncated?void 0:initialState(),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state,pending){if(state.status!=="open"||pending.round!==state.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state=value;if(state.pending){let pending=state.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path262,record3){mkdirSync69(dirname106(path262),{recursive:!0});let descriptor=openSync28(path262,"a");try{writeSync4(descriptor,`${JSON.stringify(record3)}
|
|
6593
|
-
`,void 0,"utf8"),fsyncSync9(descriptor)}finally{closeSync28(descriptor)}}function readAuditTail(path262,scope){if(!
|
|
6593
|
+
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();import{existsSync as existsSync137,mkdirSync as mkdirSync68,readFileSync as readFileSync103}from"node:fs";import{join as join207}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals202={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key of Object.keys(source)){if(FORBIDDEN_KEYS.has(key))continue;let value=source[key];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key]=nested}else if(Array.isArray(value))target[key]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join207(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync68(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals202.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync137(filePath))try{let raw=readFileSync103(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync103(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_lock();init_task_file();import{createHash as createHash55,randomUUID as randomUUID30}from"node:crypto";import{closeSync as closeSync28,existsSync as existsSync138,fsyncSync as fsyncSync9,mkdirSync as mkdirSync69,openSync as openSync28,readFileSync as readFileSync104,readSync as readSync19,statSync as statSync57,writeSync as writeSync4}from"node:fs";import{dirname as dirname106,join as join208}from"node:path";var VERSION=1,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha2565(value){return createHash55("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");return`task-${sha2565(scope.taskId)}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");return`phase-${scope.phaseNumber}`}if(typeof scope.generation!=="string"||scope.generation.length===0||scope.generation.length>256)throw Error("invalid final council scope");return`final-${sha2565(scope.generation)}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha2565(scope.taskId)};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber};return{kind:"final",scopeHash:sha2565(scope.generation)}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join208(directory,".swarm","council","round-state",`${token}.json`),audit:join208(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join208("council","round-state",`${token}.json`)}}function canonicalize2(value){if(Array.isArray(value))return value.map(canonicalize2);if(value&&typeof value==="object"){let result=Object.create(null);for(let key of Object.keys(value).sort()){if(key==="working_directory"||key==="roundNumber"||key==="provenanceAgentName"||key==="provenanceSessionId")continue;result[key]=canonicalize2(value[key])}return result}return value}function councilRequestDigest(request,round){return sha2565(JSON.stringify({round,request:canonicalize2(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state=value;return state.version===VERSION&&isRound(state.currentRound)&&(state.status==="open"||state.status==="closed")&&typeof state.maxRoundsExhausted==="boolean"&&(state.lastAttemptId===void 0||isUuid2(state.lastAttemptId))&&(state.lastDigest===void 0||isDigest(state.lastDigest))&&state.lastAttemptId===void 0===(state.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2){let current=tail2.truncated?void 0:initialState(),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state,pending){if(state.status!=="open"||pending.round!==state.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===state.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state=value;if(state.pending){let pending=state.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path262,record3){mkdirSync69(dirname106(path262),{recursive:!0});let descriptor=openSync28(path262,"a");try{writeSync4(descriptor,`${JSON.stringify(record3)}
|
|
6594
|
+
`,void 0,"utf8"),fsyncSync9(descriptor)}finally{closeSync28(descriptor)}}function readAuditTail(path262,scope){if(!existsSync138(path262))return{records:[],truncated:!1};let size=statSync57(path262).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync28(path262,"r"),buffer=Buffer.alloc(length);try{readSync19(descriptor,buffer,0,length,offset)}finally{closeSync28(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
|
|
6594
6595
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
6595
6596
|
`);if(firstNewline<0)throw new CouncilRoundStateUncertainError("council attempt audit tail is oversized");text=text.slice(firstNewline+1)}let expectedScope=auditScope(scope);return{records:text.split(`
|
|
6596
|
-
`).filter(Boolean).map((line)=>parseAuditRecord(line,expectedScope)),truncated:offset>0}}function initialState(){return{version:VERSION,currentRound:1,status:"open",maxRoundsExhausted:!1}}function snapshot(state){return{version:VERSION,currentRound:state.currentRound,status:state.status,maxRoundsExhausted:state.maxRoundsExhausted,lastAttemptId:state.lastAttemptId,lastDigest:state.lastDigest}}function sameSnapshot2(left,right){return left.version===right.version&&left.currentRound===right.currentRound&&left.status===right.status&&left.maxRoundsExhausted===right.maxRoundsExhausted&&left.lastAttemptId===right.lastAttemptId&&left.lastDigest===right.lastDigest}function pendingTerminalMatches(state,record3){let pending=state.pending;if(!pending||record3.attemptId!==pending.attemptId||record3.digest!==pending.digest||record3.authoritativeRound!==pending.round||!record3.nextState)return!1;if(record3.event==="finalized")return record3.disposition===pending.disposition&&record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,pending.nextState);if(record3.event!=="recovered")return!1;if(record3.disposition==="pending_evidence_recovered")return record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,pending.nextState);if(record3.disposition!=="orphan_recovered")return!1;return record3.transition==="stay"&&record3.gateEffect==="none"&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,{...snapshot(state),lastAttemptId:pending.attemptId,lastDigest:pending.digest})}function transitionState(state,attemptId,digest3,transition,maxRounds){let configuredLimit=Math.max(1,Math.min(MAX_ROUND,maxRounds)),limit=Math.max(state.currentRound,configuredLimit),currentRound=state.currentRound,status="open",maxRoundsExhausted=state.maxRoundsExhausted;if(transition==="advance")if(currentRound<limit)currentRound++,maxRoundsExhausted=!1;else maxRoundsExhausted=!0;else if(transition==="close")status="closed";return{version:VERSION,currentRound,status,maxRoundsExhausted,lastAttemptId:attemptId,lastDigest:digest3}}async function writeState3(path262,state){mkdirSync69(dirname106(path262),{recursive:!0}),await _internals203.atomicWrite(path262,JSON.stringify(state,null,2))}function baseRecord(input,attemptId,digest3,round,disposition){return{version:VERSION,attemptId,timestamp:_internals203.now(),scope:auditScope(input.scope),clientRound:input.clientRound,authoritativeRound:round,digest:digest3,sessionHash:input.sessionID?sha2565(input.sessionID):void 0,disposition:disposition.slice(0,80),verdictCount:Math.max(0,Math.min(5,input.verdictCount)),members:input.members.slice(0,5).map((member)=>member.slice(0,32))}}function latestRecord(records,attemptId){for(let index=records.length-1;index>=0;index--)if(records[index]?.attemptId===attemptId)return records[index];return}async function loadState2(paths,scope){if(existsSync137(paths.state))return parseState(readFileSync104(paths.state,"utf8"));let tail2=_internals203.readAuditTail(paths.audit,scope),records=tail2.records,recovered=recoverAuditHistory(tail2);if(tail2.truncated&&!recovered)throw new CouncilRoundStateUncertainError("council state is missing and the bounded audit tail has no recoverable transition");if(!recovered&&records.length>0)throw new CouncilRoundStateUncertainError("council state is missing and the audit has no complete transition");let state=recovered??initialState();return await writeState3(paths.state,state),state}function persistenceFailure2(round,error93){return JSON.stringify({success:!1,reason:"council_round_state_persistence_failed",authoritativeRound:round,message:error93 instanceof Error?error93.message:String(error93)},null,2)}function uncertainFailure(error93){return JSON.stringify({success:!1,reason:"council_round_state_uncertain",message:error93 instanceof Error?error93.message:String(error93)},null,2)}async function runCouncilAttempt(input){let paths=councilRoundStatePaths(input.directory,input.scope),authoritativeRound=1;try{return await _internals203.withLock(input.directory,paths.lock,STATE_AGENT,scopeToken(input.scope),async()=>{let state=await loadState2(paths,input.scope);if(state.pending){let tail2=_internals203.readAuditTail(paths.audit,input.scope),latest=latestRecord(tail2.records,state.pending.attemptId);if(tail2.truncated&&!latest)throw new CouncilRoundStateUncertainError("pending council attempt is outside the bounded audit tail");if(!latest)throw new CouncilRoundStateUncertainError("pending council attempt has no matching audit record");if((latest.event==="finalized"||latest.event==="recovered")&&latest.nextState){if(!pendingTerminalMatches(state,latest))throw new CouncilRoundStateUncertainError("terminal council audit contradicts pending state");state=latest.nextState}else{let committed=state.pending.evidenceExpected&&input.probePendingEvidence?await input.probePendingEvidence(state.pending.attemptId,state.pending.round,state.pending.evidenceRef):!1,recovered=committed?state.pending.nextState:{...snapshot(state),lastAttemptId:state.pending.attemptId,lastDigest:state.pending.digest};_internals203.appendAudit(paths.audit,{...baseRecord(input,state.pending.attemptId,state.pending.digest,state.pending.round,committed?"pending_evidence_recovered":"orphan_recovered"),event:"recovered",transition:committed?state.pending.transition:"stay",gateEffect:committed?state.pending.gateEffect:"none",verdict:state.pending.verdict,quorumSize:state.pending.quorumSize,evidenceRef:state.pending.evidenceRef,nextState:recovered}),state=recovered}await writeState3(paths.state,state)}authoritativeRound=state.currentRound;let digest3=councilRequestDigest(input.request,authoritativeRound),attemptId=_internals203.uuid(),received=baseRecord(input,attemptId,digest3,authoritativeRound,"received");if(_internals203.appendAudit(paths.audit,{...received,event:"received"}),input.clientRound!==void 0&&input.clientRound!==authoritativeRound){let next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_round_mismatch",transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:"council_round_mismatch",authoritativeRound,submittedRound:input.clientRound},null,2)}if(state.status==="closed"){let disposition=state.lastDigest===digest3?"duplicate_submission":"council_round_closed",next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition,transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:disposition,authoritativeRound},null,2)}let evaluation;try{evaluation=await input.evaluate(authoritativeRound)}catch(error93){evaluation={disposition:"council_evaluation_failed",response:{success:!1,reason:"council_evaluation_failed",message:error93 instanceof Error?error93.message:String(error93)},transition:"stay",gateEffect:"none"}}let next=transitionState(state,attemptId,digest3,evaluation.transition,input.maxRounds),pending={attemptId,digest:digest3,round:authoritativeRound,transition:evaluation.transition,nextState:next,disposition:evaluation.disposition.slice(0,80),gateEffect:evaluation.gateEffect,evidenceExpected:Boolean(evaluation.evidence),evidenceRef:evaluation.evidence?.reference.slice(0,240),verdict:evaluation.verdict,quorumSize:evaluation.quorumSize};try{await writeState3(paths.state,{...snapshot(state),pending})}catch(error93){let failed={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};_internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_pending_state_write_failed",transition:"stay",gateEffect:"none",nextState:failed});try{await writeState3(paths.state,failed)}catch{}throw error93}await evaluation.evidence?.commit(attemptId),_internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:evaluation.disposition.slice(0,80),transition:evaluation.transition,gateEffect:evaluation.gateEffect,verdict:evaluation.verdict,quorumSize:evaluation.quorumSize,evidenceRef:evaluation.evidence?.reference.slice(0,240),nextState:next}),await writeState3(paths.state,next);try{await evaluation.afterCommit?.()}catch{}return JSON.stringify({...evaluation.response,authoritativeRound,nextRound:next.currentRound,maxRoundsExhausted:next.maxRoundsExhausted},null,2)})}catch(error93){if(await recordUnscopedCouncilAttempt(input.directory,input.scope.kind,error93 instanceof CouncilRoundStateUncertainError?"council_round_state_uncertain":"council_round_state_persistence_failed",input.request,[],input.sessionID),error93 instanceof CouncilRoundStateUncertainError)return uncertainFailure(error93);return persistenceFailure2(authoritativeRound,error93)}}async function recordUnscopedCouncilAttempt(directory,level,disposition,raw,issues,sessionID){let path262=join208(directory,".swarm","council","attempts","unscoped.jsonl"),known=raw&&typeof raw==="object"?raw:{},fingerprint2=sha2565(JSON.stringify({level,taskIdType:typeof known.taskId,phaseType:typeof known.phase,phaseNumberType:typeof known.phaseNumber,roundNumberType:typeof known.roundNumber,verdictCount:Array.isArray(known.verdicts)?Math.min(6,known.verdicts.length):-1,issues:issues.slice(0,20).map((issue3)=>({path:issue3.path.slice(0,8).map(String),code:issue3.code.slice(0,40)}))}));try{return await _internals203.withLock(directory,join208("council","attempts","unscoped.jsonl"),STATE_AGENT,"unscoped",async()=>{mkdirSync69(dirname106(path262),{recursive:!0});let descriptor=openSync28(path262,"a");try{writeSync4(descriptor,`${JSON.stringify({version:VERSION,event:"unscoped",attemptId:_internals203.uuid(),timestamp:_internals203.now(),level,disposition:disposition.slice(0,80),fingerprint:fingerprint2,sessionHash:sessionID?sha2565(sessionID):void 0})}
|
|
6597
|
+
`).filter(Boolean).map((line)=>parseAuditRecord(line,expectedScope)),truncated:offset>0}}function initialState(){return{version:VERSION,currentRound:1,status:"open",maxRoundsExhausted:!1}}function snapshot(state){return{version:VERSION,currentRound:state.currentRound,status:state.status,maxRoundsExhausted:state.maxRoundsExhausted,lastAttemptId:state.lastAttemptId,lastDigest:state.lastDigest}}function sameSnapshot2(left,right){return left.version===right.version&&left.currentRound===right.currentRound&&left.status===right.status&&left.maxRoundsExhausted===right.maxRoundsExhausted&&left.lastAttemptId===right.lastAttemptId&&left.lastDigest===right.lastDigest}function pendingTerminalMatches(state,record3){let pending=state.pending;if(!pending||record3.attemptId!==pending.attemptId||record3.digest!==pending.digest||record3.authoritativeRound!==pending.round||!record3.nextState)return!1;if(record3.event==="finalized")return record3.disposition===pending.disposition&&record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,pending.nextState);if(record3.event!=="recovered")return!1;if(record3.disposition==="pending_evidence_recovered")return record3.transition===pending.transition&&record3.gateEffect===pending.gateEffect&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,pending.nextState);if(record3.disposition!=="orphan_recovered")return!1;return record3.transition==="stay"&&record3.gateEffect==="none"&&record3.verdict===pending.verdict&&record3.quorumSize===pending.quorumSize&&record3.evidenceRef===pending.evidenceRef&&sameSnapshot2(record3.nextState,{...snapshot(state),lastAttemptId:pending.attemptId,lastDigest:pending.digest})}function transitionState(state,attemptId,digest3,transition,maxRounds){let configuredLimit=Math.max(1,Math.min(MAX_ROUND,maxRounds)),limit=Math.max(state.currentRound,configuredLimit),currentRound=state.currentRound,status="open",maxRoundsExhausted=state.maxRoundsExhausted;if(transition==="advance")if(currentRound<limit)currentRound++,maxRoundsExhausted=!1;else maxRoundsExhausted=!0;else if(transition==="close")status="closed";return{version:VERSION,currentRound,status,maxRoundsExhausted,lastAttemptId:attemptId,lastDigest:digest3}}async function writeState3(path262,state){mkdirSync69(dirname106(path262),{recursive:!0}),await _internals203.atomicWrite(path262,JSON.stringify(state,null,2))}function baseRecord(input,attemptId,digest3,round,disposition){return{version:VERSION,attemptId,timestamp:_internals203.now(),scope:auditScope(input.scope),clientRound:input.clientRound,authoritativeRound:round,digest:digest3,sessionHash:input.sessionID?sha2565(input.sessionID):void 0,disposition:disposition.slice(0,80),verdictCount:Math.max(0,Math.min(5,input.verdictCount)),members:input.members.slice(0,5).map((member)=>member.slice(0,32))}}function latestRecord(records,attemptId){for(let index=records.length-1;index>=0;index--)if(records[index]?.attemptId===attemptId)return records[index];return}async function loadState2(paths,scope){if(existsSync138(paths.state))return parseState(readFileSync104(paths.state,"utf8"));let tail2=_internals203.readAuditTail(paths.audit,scope),records=tail2.records,recovered=recoverAuditHistory(tail2);if(tail2.truncated&&!recovered)throw new CouncilRoundStateUncertainError("council state is missing and the bounded audit tail has no recoverable transition");if(!recovered&&records.length>0)throw new CouncilRoundStateUncertainError("council state is missing and the audit has no complete transition");let state=recovered??initialState();return await writeState3(paths.state,state),state}function persistenceFailure2(round,error93){return JSON.stringify({success:!1,reason:"council_round_state_persistence_failed",authoritativeRound:round,message:error93 instanceof Error?error93.message:String(error93)},null,2)}function uncertainFailure(error93){return JSON.stringify({success:!1,reason:"council_round_state_uncertain",message:error93 instanceof Error?error93.message:String(error93)},null,2)}async function runCouncilAttempt(input){let paths=councilRoundStatePaths(input.directory,input.scope),authoritativeRound=1;try{return await _internals203.withLock(input.directory,paths.lock,STATE_AGENT,scopeToken(input.scope),async()=>{let state=await loadState2(paths,input.scope);if(state.pending){let tail2=_internals203.readAuditTail(paths.audit,input.scope),latest=latestRecord(tail2.records,state.pending.attemptId);if(tail2.truncated&&!latest)throw new CouncilRoundStateUncertainError("pending council attempt is outside the bounded audit tail");if(!latest)throw new CouncilRoundStateUncertainError("pending council attempt has no matching audit record");if((latest.event==="finalized"||latest.event==="recovered")&&latest.nextState){if(!pendingTerminalMatches(state,latest))throw new CouncilRoundStateUncertainError("terminal council audit contradicts pending state");state=latest.nextState}else{let committed=state.pending.evidenceExpected&&input.probePendingEvidence?await input.probePendingEvidence(state.pending.attemptId,state.pending.round,state.pending.evidenceRef):!1,recovered=committed?state.pending.nextState:{...snapshot(state),lastAttemptId:state.pending.attemptId,lastDigest:state.pending.digest};_internals203.appendAudit(paths.audit,{...baseRecord(input,state.pending.attemptId,state.pending.digest,state.pending.round,committed?"pending_evidence_recovered":"orphan_recovered"),event:"recovered",transition:committed?state.pending.transition:"stay",gateEffect:committed?state.pending.gateEffect:"none",verdict:state.pending.verdict,quorumSize:state.pending.quorumSize,evidenceRef:state.pending.evidenceRef,nextState:recovered}),state=recovered}await writeState3(paths.state,state)}authoritativeRound=state.currentRound;let digest3=councilRequestDigest(input.request,authoritativeRound),attemptId=_internals203.uuid(),received=baseRecord(input,attemptId,digest3,authoritativeRound,"received");if(_internals203.appendAudit(paths.audit,{...received,event:"received"}),input.clientRound!==void 0&&input.clientRound!==authoritativeRound){let next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_round_mismatch",transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:"council_round_mismatch",authoritativeRound,submittedRound:input.clientRound},null,2)}if(state.status==="closed"){let disposition=state.lastDigest===digest3?"duplicate_submission":"council_round_closed",next2={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};return _internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition,transition:"stay",gateEffect:"none",nextState:next2}),await writeState3(paths.state,next2),JSON.stringify({success:!1,reason:disposition,authoritativeRound},null,2)}let evaluation;try{evaluation=await input.evaluate(authoritativeRound)}catch(error93){evaluation={disposition:"council_evaluation_failed",response:{success:!1,reason:"council_evaluation_failed",message:error93 instanceof Error?error93.message:String(error93)},transition:"stay",gateEffect:"none"}}let next=transitionState(state,attemptId,digest3,evaluation.transition,input.maxRounds),pending={attemptId,digest:digest3,round:authoritativeRound,transition:evaluation.transition,nextState:next,disposition:evaluation.disposition.slice(0,80),gateEffect:evaluation.gateEffect,evidenceExpected:Boolean(evaluation.evidence),evidenceRef:evaluation.evidence?.reference.slice(0,240),verdict:evaluation.verdict,quorumSize:evaluation.quorumSize};try{await writeState3(paths.state,{...snapshot(state),pending})}catch(error93){let failed={...snapshot(state),lastAttemptId:attemptId,lastDigest:digest3};_internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:"council_pending_state_write_failed",transition:"stay",gateEffect:"none",nextState:failed});try{await writeState3(paths.state,failed)}catch{}throw error93}await evaluation.evidence?.commit(attemptId),_internals203.appendAudit(paths.audit,{...received,event:"finalized",disposition:evaluation.disposition.slice(0,80),transition:evaluation.transition,gateEffect:evaluation.gateEffect,verdict:evaluation.verdict,quorumSize:evaluation.quorumSize,evidenceRef:evaluation.evidence?.reference.slice(0,240),nextState:next}),await writeState3(paths.state,next);try{await evaluation.afterCommit?.()}catch{}return JSON.stringify({...evaluation.response,authoritativeRound,nextRound:next.currentRound,maxRoundsExhausted:next.maxRoundsExhausted},null,2)})}catch(error93){if(await recordUnscopedCouncilAttempt(input.directory,input.scope.kind,error93 instanceof CouncilRoundStateUncertainError?"council_round_state_uncertain":"council_round_state_persistence_failed",input.request,[],input.sessionID),error93 instanceof CouncilRoundStateUncertainError)return uncertainFailure(error93);return persistenceFailure2(authoritativeRound,error93)}}async function recordUnscopedCouncilAttempt(directory,level,disposition,raw,issues,sessionID){let path262=join208(directory,".swarm","council","attempts","unscoped.jsonl"),known=raw&&typeof raw==="object"?raw:{},fingerprint2=sha2565(JSON.stringify({level,taskIdType:typeof known.taskId,phaseType:typeof known.phase,phaseNumberType:typeof known.phaseNumber,roundNumberType:typeof known.roundNumber,verdictCount:Array.isArray(known.verdicts)?Math.min(6,known.verdicts.length):-1,issues:issues.slice(0,20).map((issue3)=>({path:issue3.path.slice(0,8).map(String),code:issue3.code.slice(0,40)}))}));try{return await _internals203.withLock(directory,join208("council","attempts","unscoped.jsonl"),STATE_AGENT,"unscoped",async()=>{mkdirSync69(dirname106(path262),{recursive:!0});let descriptor=openSync28(path262,"a");try{writeSync4(descriptor,`${JSON.stringify({version:VERSION,event:"unscoped",attemptId:_internals203.uuid(),timestamp:_internals203.now(),level,disposition:disposition.slice(0,80),fingerprint:fingerprint2,sessionHash:sessionID?sha2565(sessionID):void 0})}
|
|
6597
6598
|
`,void 0,"utf8"),fsyncSync9(descriptor)}finally{closeSync28(descriptor)}}),null}catch(error93){return persistenceFailure2(1,error93)}}var _internals203={now:()=>new Date().toISOString(),uuid:randomUUID30,appendAudit:appendAudit2,readAuditTail,atomicWrite:atomicWriteFile,withLock:withEvidenceLock};var COUNCIL_DEFAULTS={enabled:!1,maxRounds:3,parallelTimeoutMs:30000,vetoPriority:!0,requireAllMembers:!1,minimumMembers:3,phaseConcernsAllowComplete:!0};function synthesizeCouncilVerdicts(taskId,swarmId,verdicts,criteria,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),allAssessedIds=new Set(verdicts.flatMap((v)=>v.criteriaAssessed)),allUnmetIds=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)),allCriteriaMet=[...new Set((criteria?.criteria??[]).filter((c)=>c.mandatory).map((c)=>c.id))].every((id)=>allAssessedIds.has(id)&&!allUnmetIds.has(id)),unifiedFeedbackMd=buildUnifiedFeedback(taskId,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{taskId,swarmId,timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,...verdicts.length===0&&{emptyVerdictsWarning:!0}}}function promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings){let blocking=verdicts.filter((v)=>v.verdict==="CONCERNS"&&!rejectingSet.has(v.agent)).flatMap((v)=>v.findings).filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH");if(blocking.length===0)return 0;requiredFixes.push(...blocking);let blockingSet=new Set(blocking);for(let i=advisoryFindings.length-1;i>=0;i--)if(blockingSet.has(advisoryFindings[i]))advisoryFindings.splice(i,1);return blocking.length}function detectConflicts2(verdicts){let conflicts=[],locationMap=new Map;for(let verdict of verdicts)for(let finding of verdict.findings){let key=finding.location.toLowerCase();if(!key)continue;let entries=locationMap.get(key);if(entries)entries.push({agent:verdict.agent,detail:finding.detail});else locationMap.set(key,[{agent:verdict.agent,detail:finding.detail}])}for(let[location,entries]of locationMap){if(entries.length<2)continue;let addDirectives=entries.filter((e)=>/\badd\b|\binclude\b|\binsert\b/i.test(e.detail)),removeDirectives=entries.filter((e)=>/\bremove\b|\bdelete\b|\beliminate\b/i.test(e.detail));if(addDirectives.length>0&&removeDirectives.length>0)conflicts.push(`Conflict at ${location}: ${addDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")} vs ${removeDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")}`)}return conflicts}function buildUnifiedFeedback(taskId,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Work Complete Council — Round ${roundNumber}/${maxRounds}`,`**Task:** ${taskId} **Overall verdict:** ${verdict}`,""];if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before advancement.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **All council members approved.** Work may advance to `complete`.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
|
|
6598
6599
|
`)}function synthesizePhaseCouncilAdvisory(phaseNumber,phaseSummary,verdicts,roundNumber,config3={},_workingDir){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),scope="phase",quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Phase ${phaseNumber} council found ${advisoryFindings.length} advisory finding(s). Review before proceeding to next phase.`);if(verdicts.length<3)advisoryNotes.push(`Phase council quorum is ${verdicts.length} members — consider convening additional members for broader review coverage.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildPhaseCouncilFeedback(phaseNumber,phaseSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount),evidencePath=`.swarm/evidence/${phaseNumber}/phase-council.json`;return{phaseNumber,scope:"phase",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,evidencePath,phaseSummary}}function buildPhaseCouncilFeedback(phaseNumber,phaseSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Phase Council Review — Round ${roundNumber}/${maxRounds}`,`**Phase:** ${phaseNumber} **Overall verdict:** ${verdict}`,""];if(phaseSummary)lines.push(`**Phase Summary:** ${phaseSummary}`),lines.push("");if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before phase completion.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **Phase council approved.** Phase may proceed to completion.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
|
|
6599
6600
|
`)}function synthesizeFinalCouncilAdvisory(projectSummary,verdicts,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Final council found ${advisoryFindings.length} advisory finding(s). Review before project close.`);if(quorumSize<3)advisoryNotes.push(`Final council quorum is ${quorumSize} members - dispatch additional project-scoped council members before closing the project.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildFinalCouncilFeedback(projectSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{scope:"project",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,evidencePath:".swarm/evidence/final-council.json",blockingConcernsCount,projectSummary}}function buildFinalCouncilFeedback(projectSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Final Council Review - Round ${roundNumber}/${maxRounds}`,`**Scope:** completed project **Overall verdict:** ${verdict}`,""];if(projectSummary)lines.push(`**Project Summary:** ${projectSummary}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before project close.`),lines.push("");if(vetoedBy.length>0)lines.push(`> BLOCKED: project close is blocked by ${vetoedBy.join(", ")}`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before project close)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following council members gave contradictory project-close instructions. Architect must resolve before closing the project._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> Final council approved. Project may proceed to close.");else if(roundNumber>=maxRounds)lines.push(`> Max rounds (${maxRounds}) reached. Escalate to user - do not close the project automatically.`);return lines.join(`
|
|
6600
|
-
`)}init_zod();init_task_file();init_project_boundary();import{existsSync as
|
|
6601
|
+
`)}init_zod();init_task_file();init_project_boundary();import{existsSync as existsSync139,mkdirSync as mkdirSync70,readFileSync as readFileSync105}from"node:fs";import{join as join209}from"node:path";var COUNCIL_DIR=".swarm/council",CouncilCriteriaSchema=exports_external.object({taskId:exports_external.string(),criteria:exports_external.array(exports_external.object({id:exports_external.string(),description:exports_external.string(),mandatory:exports_external.boolean()})),declaredAt:exports_external.string()});async function writeCriteria(workingDir,taskId,criteria){assertProjectRoot(workingDir);let dir=join209(workingDir,COUNCIL_DIR);mkdirSync70(dir,{recursive:!0});let payload={taskId,criteria,declaredAt:new Date().toISOString()};await atomicWriteFile(join209(dir,`${safeId(taskId)}.json`),JSON.stringify(payload,null,2))}function readCriteria(workingDir,taskId){let filePath=join209(workingDir,COUNCIL_DIR,`${safeId(taskId)}.json`);if(!existsSync139(filePath))return null;try{return CouncilCriteriaSchema.parse(JSON.parse(readFileSync105(filePath,"utf-8")))}catch{return null}}function safeId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_")}init_state2();init_create_tool();init_resolve_working_directory();var ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],FindingSchema=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema=exports_external.object({agent:exports_external.enum(ALL_MEMBERS),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema=exports_external.object({taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g. "1.1")'),swarmId:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema).min(1).max(5),working_directory:exports_external.string().optional()});function invalidResponse(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}var submit_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for synthesis. PREREQUISITE — "+"dispatch critic, reviewer, sme, test_engineer, and explorer as separate Agent tasks, then submit their real verdicts here. The server owns the current council round; roundNumber is only an optional expectation. Architect-only and config-gated.",args:{taskId:ArgsSchema.shape.taskId.describe('Task ID, e.g. "1.1"'),swarmId:ArgsSchema.shape.swarmId.describe('Swarm identifier, e.g. "mega"'),roundNumber:ArgsSchema.shape.roundNumber.describe("Optional expected server round. Omit to use the authoritative current round."),verdicts:ArgsSchema.shape.verdicts.describe("Collected CouncilMemberVerdict objects from dispatched council members."),working_directory:ArgsSchema.shape.working_directory.describe("Explicit project root directory.")},async execute(args2,directory,ctx){let parsed=ArgsSchema.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"task","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse(parsed.error.issues);let input=parsed.data,resolved=resolveWorkingDirectory(input.working_directory,directory);if(!resolved.success)return await recordUnscopedCouncilAttempt(directory,"task","invalid_working_directory",input,[],ctx?.sessionID)??JSON.stringify({success:!1,reason:resolved.message},null,2);let workingDir=resolved.directory,councilConfig=loadPluginConfig(workingDir).council,distinctMembers=new Set(input.verdicts.map((verdict)=>verdict.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((member)=>!distinctMembers.has(member)),session=ctx?.sessionID?getAgentSession(ctx.sessionID):void 0,councilWorkflowGeneration=session?.taskCouncilWorkflowGeneration?.get(input.taskId);return runCouncilAttempt({directory:workingDir,scope:{kind:"task",taskId:input.taskId},clientRound:input.roundNumber,maxRounds:councilConfig?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasCouncilEvidenceAttempt(workingDir,input.taskId,attemptId,round),evaluate:async(authoritativeRound)=>{if(!councilConfig?.enabled)return{disposition:"council_disabled",response:{success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},transition:"stay",gateEffect:"none"};let effectiveMinimum=councilConfig.requireAllMembers?5:councilConfig.minimumMembers??3,requirementKey=`${input.taskId}:${authoritativeRound}`;if(session&&!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;let required3=session?.pendingCouncilRequirements?.get(requirementKey),stillMissingMembers=required3?[...required3].filter((member)=>!distinctMembers.has(member)):[];if(stillMissingMembers.length>0)return{disposition:"cherry_pick_detected",response:{success:!1,reason:"cherry_pick_detected",message:`Incomplete re-dispatch: ${stillMissingMembers.join(", ")} were required from the previous insufficient_quorum response but are still absent. Dispatch ALL absent members in one parallel batch.`,stillMissingMembers,membersProvided:membersVoted},transition:"stay",gateEffect:"none"};if(membersVoted.length<effectiveMinimum)return session?.pendingCouncilRequirements?.set(requirementKey,new Set(membersAbsent)),{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members before resubmitting.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},transition:"stay",gateEffect:"none"};let synthesis=synthesizeCouncilVerdicts(input.taskId,input.swarmId,input.verdicts,readCriteria(workingDir,input.taskId),authoritativeRound,councilConfig),dissenters=synthesis.memberVerdicts.filter((verdict)=>verdict.verdict==="CONCERNS"||verdict.verdict==="REJECT").map((verdict)=>verdict.agent),updateRequirements=(transition2)=>{if(!session?.pendingCouncilRequirements)return;if(session.pendingCouncilRequirements.delete(requirementKey),transition2==="advance"&&dissenters.length>0){let nextRequiredRound=Math.min(authoritativeRound+1,Math.max(authoritativeRound,councilConfig.maxRounds));session.pendingCouncilRequirements.set(`${input.taskId}:${nextRequiredRound}`,new Set(dissenters))}};if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Council returned CONCERNS with ${synthesis.blockingConcernsCount} blocking finding(s). Address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length,afterCommit:()=>updateRequirements("advance")};let transition=synthesis.overallVerdict==="REJECT"?"advance":"close";return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},transition,gateEffect:transition==="close"?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length,evidence:{reference:`.swarm/evidence/${input.taskId}.json`,commit:async(attemptId)=>{if(councilWorkflowGeneration===void 0)throw Error(`TASK_COUNCIL_GENERATION_REQUIRED: dispatch council members for task ${input.taskId} before submitting their verdicts`);await writeCouncilEvidence(workingDir,synthesis,attemptId,councilWorkflowGeneration)}},afterCommit:async()=>{updateRequirements(transition);try{if(ctx?.sessionID&&session)pushCouncilAdvisory(session,synthesis)}catch{}}}}})}});init_zod();init_loader();import*as fs150 from"node:fs";import*as path262 from"node:path";var ADVISORY_HEADER="[general_council] (advisory; not blocking)";function pushGeneralCouncilAdvisory(session,result){if(!session)return;let body=renderAdvisoryBody(result);if(!body)return;pushAdvisory(session,`${ADVISORY_HEADER}
|
|
6601
6602
|
${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var EXPLICIT_DISAGREEMENT_MARKERS=["i disagree with","i would push back on","contrary to","this contradicts","unlike "],STRONG_RECOMMENDATION_MARKERS=["recommend","best approach","should use","i suggest","the answer is","the right choice is"];function tokenize3(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=3)}function termOverlap(a,b){let tokensA=new Set(tokenize3(a)),tokensB=new Set(tokenize3(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractMarkerSentence(response,markers){let lower=response.toLowerCase(),sentences=response.split(/(?<=[.!?])\s+/);for(let sentence of sentences){let sentLower=sentence.toLowerCase();if(markers.some((m)=>sentLower.includes(m)))return sentence.trim()}for(let marker of markers){let idx=lower.indexOf(marker);if(idx!==-1){let slice=response.slice(idx,idx+200);return slice.split(/\n/)[0]?.trim()??slice.trim()}}return null}function dedupeByTopic(disagreements){let result=[];for(let d of disagreements){let topicLower=d.topic.toLowerCase(),existing=result.find((r)=>r.topic.toLowerCase().includes(topicLower)||topicLower.includes(r.topic.toLowerCase()));if(existing){for(let pos of d.positions)if(!existing.positions.some((p)=>p.memberId===pos.memberId))existing.positions.push(pos)}else result.push(d)}return result}function detectExplicitMarkers(responses){let out=[];for(let member of responses){let markerSentence=extractMarkerSentence(member.response,EXPLICIT_DISAGREEMENT_MARKERS);if(!markerSentence)continue;let position={memberId:member.memberId,claim:markerSentence,evidence:member.sources[0]?.url??"(no source cited in marker sentence)"};out.push({topic:markerSentence.slice(0,80),positions:[position]})}return out}function extractRecommendation(response){return extractMarkerSentence(response,STRONG_RECOMMENDATION_MARKERS)}function detectClaimDivergence(responses){let recommendations=[];for(let member of responses){let rec=extractRecommendation(member.response);if(!rec)continue;recommendations.push({memberId:member.memberId,text:rec,evidence:member.sources[0]?.url??"(no source cited)"})}let out=[];for(let i=0;i<recommendations.length;i++)for(let j=i+1;j<recommendations.length;j++){let a=recommendations[i],b=recommendations[j];if(!a||!b)continue;let topicOverlap=termOverlap(a.text,b.text);if(topicOverlap>0.4)continue;if(topicOverlap>0&&topicOverlap<0.3){let topic=`${a.text.slice(0,50)} vs ${b.text.slice(0,50)}`;out.push({topic,positions:[{memberId:a.memberId,claim:a.text,evidence:a.evidence},{memberId:b.memberId,claim:b.text,evidence:b.evidence}]})}}return out}function detectDisagreements(responses){if(!Array.isArray(responses)||responses.length<2)return[];let safeResponses=responses.filter((r)=>typeof r?.memberId==="string"&&typeof r?.response==="string"),explicit=detectExplicitMarkers(safeResponses),divergent=detectClaimDivergence(safeResponses),combined=[...explicit,...divergent];return dedupeByTopic(combined).slice(0,10)}var CONSENSUS_WEIGHT_THRESHOLD=0.6;function tokenize4(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=4)}function similarity(a,b){let tokensA=new Set(tokenize4(a)),tokensB=new Set(tokenize4(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractClaims(response){return response.split(/(?<=[.!?])\s+/).map((s)=>s.trim()).filter((s)=>s.length>=30&&s.length<=400)}function buildConsensusClusters(responses){if(responses.length<2)return[];let totalMembers=responses.length,clusters=[];for(let member of responses){let confidence=clamp012(member.confidence??0.5),claims=extractClaims(member.response??"");for(let claim of claims){let assigned=!1;for(let cluster of clusters)if(similarity(cluster.representative,claim)>=0.5){if(!cluster.memberIds.has(member.memberId))cluster.weightedAgreement+=confidence,cluster.memberIds.add(member.memberId);if(claim.length>cluster.representative.length)cluster.representative=claim;assigned=!0;break}if(!assigned)clusters.push({representative:claim,weightedAgreement:confidence,memberIds:new Set([member.memberId])})}}return clusters.filter((c)=>c.memberIds.size>=2&&c.weightedAgreement/totalMembers>=CONSENSUS_WEIGHT_THRESHOLD).sort((a,b)=>b.weightedAgreement-a.weightedAgreement||b.memberIds.size-a.memberIds.size).map((c)=>c.representative)}function clamp012(n){if(typeof n!=="number"||Number.isNaN(n))return 0;if(n<0)return 0;if(n>1)return 1;return n}function computePersistingDisagreements(disagreements,round2){if(disagreements.length===0)return[];if(round2.length===0)return disagreements;return disagreements.filter((d)=>{let disputants=new Set(d.positions.map((p)=>p.memberId));return!round2.some((r)=>{if(!disputants.has(r.memberId))return!1;if(!r.disagreementTopics?.includes(d.topic))return!1;return/\bconcede\b/i.test(r.response??"")})})}function dedupeSources(round1,round2){let seen=new Set,out=[],allSources=[...round1,...round2].flatMap((r)=>r.sources??[]);for(let src of allSources){if(!src?.url)continue;if(seen.has(src.url))continue;seen.add(src.url),out.push(src)}return out}function renderSynthesisMarkdown(question,mode,roundsCompleted,members,consensusPoints,persistingDisagreements,allSources){let memberLines=members.map((m)=>`- ${m.memberId} (${m.model}, ${m.role})`).join(`
|
|
6602
6603
|
`),consensusBlock=consensusPoints.length>0?consensusPoints.map((c)=>`- ${c}`).join(`
|
|
6603
6604
|
`):"_No consensus claims reached the weighted-agreement threshold._",disagreementsBlock=persistingDisagreements.length>0?persistingDisagreements.map((d)=>`- **${d.topic}**
|
|
@@ -6727,14 +6728,14 @@ ${scanResult.findings.filter((f)=>f.severity==="error").map((f)=>`- ${f.pattern}
|
|
|
6727
6728
|
|
|
6728
6729
|
[Content follows with threats marked for LLM awareness]
|
|
6729
6730
|
|
|
6730
|
-
${scanResult.neutralized}`;return result}catch(error93){if(error93 instanceof DOMException&&(error93.name==="TimeoutError"||error93.name==="AbortError")){if(attempt>=GITINGEST_MAX_RETRIES)throw Error("gitingest request timed out");let backoff=200*2**attempt;await delay3(backoff);continue}if(error93 instanceof Error&&error93.message.startsWith("gitingest "))throw error93;if(attempt<GITINGEST_MAX_RETRIES){let backoff=200*2**attempt;await delay3(backoff);continue}throw error93}throw Error("gitingest request failed after retries")}var gitingest=createSwarmTool({description:"Fetch a GitHub repository's full content via gitingest.com. Returns summary, directory tree, and file contents optimized for LLM analysis. Use when you need to understand an external repository's structure or code.",args:{url:exports_external.string().describe("GitHub repository URL (e.g., https://github.com/owner/repo)"),maxFileSize:exports_external.number().optional().describe("Maximum file size in bytes to include (default: 50000)"),pattern:exports_external.string().optional().describe("Glob pattern to filter files (e.g., '*.ts' or 'src/**/*.py')"),patternType:exports_external.enum(["include","exclude"]).optional().describe("Whether pattern includes or excludes matching files (default: exclude)")},async execute(args2,_directory,_ctx){return fetchGitingest(args2)}});init_zod();init_create_tool();init_path_security();import*as fs161 from"node:fs";import*as path274 from"node:path";var MAX_FILE_PATH_LENGTH2=500,MAX_SYMBOL_LENGTH=256,MAX_FILE_SIZE_BYTES7=1048576,MAX_CONSUMERS=100,SUPPORTED_EXTENSIONS2=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],BINARY_SIGNATURES2=[0,2303741511,4292411360,1195984440,626017350,1347093252],BINARY_PREFIX_BYTES2=4,BINARY_NULL_CHECK_BYTES2=8192,BINARY_NULL_THRESHOLD2=0.1;function validateFileInput(file3){if(!file3||file3.length===0)return"file is required";if(file3.length>MAX_FILE_PATH_LENGTH2)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH2}`;if(containsControlChars(file3))return"file contains control characters";if(containsPathTraversal(file3))return"file contains path traversal";return null}function validateSymbolInput(symbol3){if(symbol3===void 0||symbol3==="")return null;if(symbol3.length>MAX_SYMBOL_LENGTH)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH}`;if(containsControlChars(symbol3))return"symbol contains control characters";if(containsPathTraversal(symbol3))return"symbol contains path traversal";return null}function isBinaryFile3(filePath,buffer){let ext=path274.extname(filePath).toLowerCase();if(ext===".json"||ext===".md"||ext===".txt")return!1;if(buffer.length>=BINARY_PREFIX_BYTES2){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES2).readUInt32BE(0);for(let sig of BINARY_SIGNATURES2)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES2);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD2}function parseImports(content,targetFile,targetSymbol){let imports=[],_resolvedTarget;try{_resolvedTarget=path274.resolve(targetFile)}catch{_resolvedTarget=targetFile}let targetBasename=path274.basename(targetFile,path274.extname(targetFile)),targetWithExt=targetFile,targetWithoutExt=targetFile.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""),normalizedTargetWithExt=path274.normalize(targetWithExt).replace(/\\/g,"/"),normalizedTargetWithoutExt=path274.normalize(targetWithoutExt).replace(/\\/g,"/"),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`]+)['"`]|import\s+['"`]([^'"`]+)['"`]|require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let modulePath=match[1]||match[2]||match[3];if(!modulePath)continue;let lineNum=(content.substring(0,match.index).match(/\n/g)||[]).length+1,matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";let _normalizedModule=modulePath.replace(/^\.\//,"").replace(/^\.\.\\/,"../"),isMatch=!1,_targetDir=path274.dirname(targetFile),targetExt=path274.extname(targetFile),targetBasenameNoExt=path274.basename(targetFile,targetExt),moduleNormalized=modulePath.replace(/\\/g,"/").replace(/^\.\//,""),moduleName=modulePath.split(/[/\\]/).pop()||"",moduleNameNoExt=moduleName.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,"");if(modulePath===targetBasename||modulePath===targetBasenameNoExt||modulePath===`./${targetBasename}`||modulePath===`./${targetBasenameNoExt}`||modulePath===`../${targetBasename}`||modulePath===`../${targetBasenameNoExt}`||moduleNormalized===normalizedTargetWithExt||moduleNormalized===normalizedTargetWithoutExt||modulePath.endsWith(`/${targetBasename}`)||modulePath.endsWith(`\\${targetBasename}`)||modulePath.endsWith(`/${targetBasenameNoExt}`)||modulePath.endsWith(`\\${targetBasenameNoExt}`)||moduleNameNoExt===targetBasenameNoExt||`./${moduleNameNoExt}`===targetBasenameNoExt||moduleName===targetBasename||moduleName===targetBasenameNoExt)isMatch=!0;if(isMatch&&targetSymbol)if(importType==="namespace"||importType==="sideeffect")isMatch=!1;else{let namedMatch=matchedString.match(/import\s+\{([\s\S]*?)\}\s+from/);if(namedMatch)isMatch=namedMatch[1].split(",").map((s)=>{let parts=s.trim().split(/\s+as\s+/i),originalName=parts[0].trim(),aliasName=parts[1]?.trim();return{original:originalName,alias:aliasName}}).some(({original,alias})=>original===targetSymbol||alias===targetSymbol);else if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from/m);if(defaultMatch)isMatch=defaultMatch[1]===targetSymbol}}if(isMatch)imports.push({line:lineNum,imports:modulePath,importType,raw:matchedString.trim()})}return imports}var SKIP_DIRECTORIES4=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg"]);function findSourceFiles2(dir,files=[],stats2={skippedDirs:[],skippedFiles:0,fileErrors:[]}){let entries;try{entries=fs161.readdirSync(dir)}catch(e){return stats2.fileErrors.push({path:dir,reason:e instanceof Error?e.message:"readdir failed"}),files}entries.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries){if(SKIP_DIRECTORIES4.has(entry)){stats2.skippedDirs.push(path274.join(dir,entry));continue}let fullPath=path274.join(dir,entry),stat21;try{stat21=fs161.statSync(fullPath)}catch(e){stats2.fileErrors.push({path:fullPath,reason:e instanceof Error?e.message:"stat failed"});continue}if(stat21.isDirectory())findSourceFiles2(fullPath,files,stats2);else if(stat21.isFile()){let ext=path274.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS2.includes(ext))files.push(fullPath)}}return files}var imports=createSwarmTool({description:"Find all reverse dependencies (consumers) that import from a given file. Returns JSON with file path, line numbers, and import metadata for each consumer. Use this to understand who depends on a module before refactoring.",args:{file:exports_external.string().describe('Source file path to find importers for (e.g., "./src/utils.ts")'),symbol:exports_external.string().optional().describe('Optional specific symbol to filter imports (e.g., "MyClass")')},async execute(args2,_directory,_ctx){let typedArgs=args2,file3,symbol3;try{if(typedArgs&&typeof typedArgs==="object")file3=typedArgs.file,symbol3=typedArgs.symbol}catch{}if(file3===void 0)return JSON.stringify({error:"invalid arguments: file is required",target:"",symbol:void 0,consumers:[],count:0},null,2);let fileValidationError=validateFileInput(file3);if(fileValidationError){let errorResult={error:`invalid file: ${fileValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}let symbolValidationError=validateSymbolInput(symbol3);if(symbolValidationError){let errorResult={error:`invalid symbol: ${symbolValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}try{let targetFile=path274.resolve(file3);if(!fs161.existsSync(targetFile)){let errorResult={error:`target file not found: ${file3}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}if(!fs161.statSync(targetFile).isFile())return JSON.stringify({error:"target must be a file, not a directory",target:file3,symbol:symbol3,consumers:[],count:0},null,2);let baseDir=path274.dirname(targetFile),filesToScan=findSourceFiles2(baseDir,[],{skippedDirs:[],skippedFiles:0,fileErrors:[]}).filter((f)=>f!==targetFile).sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())).slice(0,MAX_CONSUMERS*10),consumers=[],skippedFileCount=0,totalMatchesFound=0;for(let filePath of filesToScan){if(consumers.length>=MAX_CONSUMERS)break;try{if(fs161.statSync(filePath).size>MAX_FILE_SIZE_BYTES7){skippedFileCount++;continue}let buffer=fs161.readFileSync(filePath);if(isBinaryFile3(filePath,buffer)){skippedFileCount++;continue}let content=buffer.toString("utf-8"),fileImports=parseImports(content,targetFile,symbol3);for(let imp of fileImports){if(totalMatchesFound++,consumers.length>=MAX_CONSUMERS)continue;if(consumers.some((c)=>c.file===filePath&&c.line===imp.line))continue;consumers.push({file:filePath,line:imp.line,imports:imp.imports,importType:imp.importType,raw:imp.raw})}}catch(_e){skippedFileCount++}}let result={target:file3,symbol:symbol3,consumers,count:consumers.length},parts=[];if(filesToScan.length>=MAX_CONSUMERS*10)parts.push(`Scanned ${filesToScan.length} files`);if(skippedFileCount>0)parts.push(`${skippedFileCount} skipped (size/binary/errors)`);if(consumers.length>=MAX_CONSUMERS){let hidden=totalMatchesFound-consumers.length;if(hidden>0)parts.push(`Results limited to ${MAX_CONSUMERS} consumers (${hidden} hidden)`);else parts.push(`Results limited to ${MAX_CONSUMERS} consumers`)}if(parts.length>0)result.message=`${parts.join("; ")}.`;return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_types();init_knowledge_validator();init_cohort_identity();init_worktree_identity();init_manager();init_create_tool();import{randomUUID as randomUUID33}from"node:crypto";var VALID_CATEGORIES2=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],KNOWLEDGE_ADD_FIELD_CAP=20;function mergeLessonTags(tagsInput,lesson){return dedupeCapped([...Array.isArray(tagsInput)?tagsInput:[],...inferTags(lesson)],{cap:KNOWLEDGE_ADD_FIELD_CAP})}function strArray(v){return Array.isArray(v)?dedupeCapped(v,{cap:KNOWLEDGE_ADD_FIELD_CAP}):void 0}var knowledge_add=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Store a new lesson in the knowledge base for future reference. The lesson will be available for retrieval via knowledge_recall.",args:{lesson:exports_external.string().min(15).max(280).describe("The lesson to store (15-280 characters)"),category:exports_external.enum(VALID_CATEGORIES2).describe("Knowledge category for the lesson"),tags:exports_external.array(exports_external.string()).optional().describe("Optional tags for better searchability"),scope:exports_external.string().optional().describe("Scope of the lesson (global or stack:<name>)"),applies_to_agents:exports_external.array(exports_external.string()).optional().describe('Agent roles this lesson applies to (e.g. ["coder"]). REQUIRED (or applies_to_tools) for the lesson to become active.'),applies_to_tools:exports_external.array(exports_external.string()).optional().describe('Tool names this lesson applies to (e.g. ["edit","bash"]). REQUIRED (or applies_to_agents) for the lesson to become active.'),required_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to always take. At least one predicate field (required_actions / forbidden_actions / verification_checks) is REQUIRED for the lesson to become active."),forbidden_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to never take."),verification_checks:exports_external.array(exports_external.string()).optional().describe("Checks a reviewer can run to verify compliance.")},execute:async(args2,directory)=>{let lessonInput,categoryInput,tagsInput,scopeInput;try{if(args2&&typeof args2==="object"){let obj2=args2;lessonInput=obj2.lesson,categoryInput=obj2.category,tagsInput=obj2.tags,scopeInput=obj2.scope}}catch{}if(typeof lessonInput!=="string")return JSON.stringify({success:!1,error:"lesson must be a string"});let lesson=lessonInput;if(lesson.length<15||lesson.length>280)return JSON.stringify({success:!1,error:"lesson must be between 15 and 280 characters"});if(typeof categoryInput!=="string")return JSON.stringify({success:!1,error:"category must be a string"});let category=categoryInput;if(!VALID_CATEGORIES2.includes(category))return JSON.stringify({success:!1,error:`category must be one of: ${VALID_CATEGORIES2.join(", ")}`});let tags=mergeLessonTags(tagsInput,lesson),scope=typeof scopeInput==="string"&&scopeInput.length>0?scopeInput:"global",obj=args2&&typeof args2==="object"?args2:{},actionable={applies_to_agents:strArray(obj.applies_to_agents),applies_to_tools:strArray(obj.applies_to_tools),required_actions:strArray(obj.required_actions),forbidden_actions:strArray(obj.forbidden_actions),verification_checks:strArray(obj.verification_checks)},shape=validateActionableFields(actionable);if(!shape.valid)return JSON.stringify({success:!1,error:`invalid actionability fields: ${shape.errors.join("; ")}`});let project_name="",phase_number=1;try{let plan=await loadPlan(directory);if(project_name=plan?.title??"",typeof plan?.current_phase==="number")phase_number=plan.current_phase}catch{}let producer=null;try{let[worktreeId,cohort]=await Promise.all([resolveWorktreeId(directory),resolveCohortId(directory)]);producer={cohort_id:cohort.cohortId,worktree_id:worktreeId}}catch{}let nowIso2=new Date().toISOString(),entry={id:randomUUID33(),tier:"swarm",lesson,category,tags,scope,confidence:0.5,status:"candidate",confirmed_by:[],project_name,retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,producer,revision:1,content_hash:computeContentHash(lesson),created_at:nowIso2,updated_at:nowIso2,auto_generated:!1,hive_eligible:!1,...actionable},config3,dedupThreshold=0.6;try{if(config3=loadPluginConfigWithMeta(directory).config,dedupThreshold=config3.knowledge?.dedup_threshold??0.6,config3.knowledge?.validation_enabled!==!1){let validation2=validateLesson(lesson,[],{category,scope,confidence:0.5});if(!validation2.valid)return JSON.stringify({success:!1,error:`Validation failed: ${validation2.reason}`})}}catch{}let actionability=validateActionability(entry);if(!actionability.actionable){try{await appendUnactionable(directory,entry,actionability.reason??"unactionable")}catch{}return JSON.stringify({success:!1,quarantined:!0,id:entry.id,reason:actionability.reason,hint:"Provide at least one of required_actions/forbidden_actions/verification_checks AND at least one of applies_to_agents/applies_to_tools, then retry."})}try{let maxEntries=config3?.knowledge?.swarm_max_entries??100,duplicateResponse;if(await transactKnowledge(resolveSwarmKnowledgePath(directory),(existingEntries)=>{let activeDuplicate=findActiveSwarmNearDuplicate(lesson,existingEntries,dedupThreshold);if(activeDuplicate){let result=reinforceSwarmKnowledgeEntry(activeDuplicate,{phase_number,confirmed_at:new Date().toISOString(),project_name});return duplicateResponse={id:activeDuplicate.id,reinforced:result.reinforced,idempotent:result.reason==="already_confirmed_phase",inactive:!1},result.reinforced?existingEntries:null}let inactiveDuplicate=findNearDuplicate(lesson,existingEntries,dedupThreshold);if(inactiveDuplicate)return duplicateResponse={id:inactiveDuplicate.id,reinforced:!1,idempotent:!1,inactive:!0},null;let updated=[...existingEntries,entry];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated}),duplicateResponse){if(duplicateResponse.inactive)return JSON.stringify({success:!1,id:duplicateResponse.id,message:"near-duplicate of inactive existing entry"});return JSON.stringify({success:!0,id:duplicateResponse.id,reinforced:duplicateResponse.reinforced,idempotent:duplicateResponse.idempotent,message:duplicateResponse.reinforced?"near-duplicate reinforced existing entry":"near-duplicate already confirmed for this phase"})}}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}return JSON.stringify({success:!0,id:entry.id,category})}});init_zod();init_knowledge_store();init_knowledge_validator();init_skill_invalidator();init_curation_policy();init_logger();init_create_tool();var MODES2=["archive","quarantine","purge"],TIERS=["swarm","hive"];async function loadConfigForPolicy(directory){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),{config:loaded}=loadPluginConfigWithMeta2(directory);return KnowledgeConfigSchema2.parse(loaded.knowledge??{})}var knowledge_archive=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Archive (default), quarantine, or purge a swarm or hive knowledge entry by ID, appending an immutable audit tombstone. 'archive'/'quarantine' set the entry status reversibly and hide it from recall; 'purge' hard-deletes and requires allow_purge:true.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry"),tier:exports_external.enum(TIERS).optional().describe("Knowledge tier to modify; default 'swarm'"),reason:exports_external.string().min(1).max(500).describe("Why the entry is being archived/quarantined/purged"),evidence:exports_external.string().max(1000).optional().describe('Supporting evidence (e.g. "ignored 8 times, contradicted by tests")'),mode:exports_external.enum(MODES2).optional().describe("Default 'archive'"),allow_purge:exports_external.boolean().optional().describe("Admin flag required when mode='purge'")},execute:async(args2,directory,ctx)=>{let a=args2??{},id=typeof a.id==="string"?a.id:"";if(!id)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let reason=typeof a.reason==="string"?a.reason:"";if(!reason)return JSON.stringify({success:!1,error:"reason is required"});let evidence2=typeof a.evidence==="string"?a.evidence:void 0,tier=a.tier==="hive"?"hive":"swarm",mode=a.mode==="quarantine"||a.mode==="purge"?a.mode:"archive";if(mode==="purge"&&a.allow_purge!==!0)return JSON.stringify({success:!1,error:"purge requires allow_purge:true (admin flag)"});if(mode==="quarantine"){if(tier==="hive")return JSON.stringify({success:!1,error:"quarantine via the archive tool is swarm-only; use tier:'swarm' or the /swarm knowledge quarantine command"});try{let target=(await readKnowledge(resolveSwarmKnowledgePath(directory))).find((e)=>e.id===id);if(!target)return JSON.stringify({success:!1,message:"entry not found"});let reportedBy=ctx?.agent==="architect"?"architect":"user",curationInput={directory,action:"quarantine",entryId:id,reason,evidenceScope:"cohort-wide",actorRole:ctx?.agent},curationContext={config:await loadConfigForPolicy(directory),entry:target};await quarantineEntry(directory,id,reason,reportedBy,{input:curationInput,context:curationContext})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error during quarantine"})}return JSON.stringify({success:!0,id,tier,mode,status:"quarantined"})}let knowledgePath=tier==="hive"?resolveHiveKnowledgePath2():resolveSwarmKnowledgePath(directory),found=!1,previousStatus,now2=new Date().toISOString(),resultStatus,casExpectedRevision,casExpectedContentHash;if(tier==="swarm"){let preEntries;try{preEntries=await readKnowledge(knowledgePath)}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}let preTarget=preEntries.find((e)=>e.id===id)??null;if(preTarget){let curationInput={directory,action:mode,entryId:id,reason,evidenceScope:"cohort-wide",actorRole:ctx?.agent},curationContext={config:await loadConfigForPolicy(directory),entry:preTarget},decision=await authorizeCuration(curationInput,curationContext);if(!decision.authorized)return JSON.stringify({success:!1,error:`Cohort-safety policy blocked this ${mode}: ${decision.detail}`,basis:decision.basis});casExpectedRevision=preTarget.revision,casExpectedContentHash=preTarget.content_hash}}if(tier==="swarm"&&mode==="archive"){let casResult;try{casResult=await transactKnowledgeWithCas(directory,knowledgePath,id,casExpectedRevision,casExpectedContentHash,(entry)=>{if(found=!0,previousStatus=entry.status,entry.status==="archived")return resultStatus="archived",null;return resultStatus="archived",{mutated:{...entry,status:"archived",archived_from:entry.status,archived_at:now2,updated_at:now2}}})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(casResult.casFailed)return JSON.stringify({success:!1,error:"entry changed since authorization (revision/content-hash mismatch); stale archive plan rejected"})}else try{await transactKnowledge(knowledgePath,(entries)=>{let target=entries.find((e)=>e.id===id);if(!target)return null;if(found=!0,previousStatus=target.status,mode==="purge")return warn(`[knowledge_archive] PURGE: hard-deleting ${tier} entry id=${id} actor=${ctx?.agent??"unknown"} reason=${reason}`),resultStatus="purged",entries.filter((e)=>e.id!==id);if(target.status==="archived")return resultStatus="archived",entries;return resultStatus="archived",entries.map((e)=>e.id===id?{...e,status:"archived",archived_from:target.status,archived_at:now2,updated_at:now2}:e)})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(!found)return JSON.stringify({success:!1,message:"entry not found"});return await writeArchiveTombstoneAndInvalidateSkills({directory,entryId:id,tier,actor:ctx?.agent??"unknown",reason,mode,evidence:evidence2,previousStatus,sourceLabel:"knowledge-archive"}),JSON.stringify({success:!0,id,tier,mode,previous_status:previousStatus,status:resultStatus})}});init_zod();init_config();init_knowledge_store();init_create_tool();import{existsSync as existsSync145}from"node:fs";var DEFAULT_LIMIT=10,MAX_LESSON_LENGTH=200,VALID_CATEGORIES3=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],VALID_STATUSES=["candidate","established","promoted","archived"],DEFAULT_QUERY_STATUSES=new Set(["established","promoted"]),VALID_TIERS=["swarm","hive","all"];function validateTierInput(tier){if(typeof tier!=="string")return null;let normalized=tier.toLowerCase().trim();if(VALID_TIERS.includes(normalized))return normalized;return null}function validateStatusInput(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase().trim();if(VALID_STATUSES.includes(normalized))return normalized;return null}function validateCategoryInput(category){if(typeof category!=="string")return null;let normalized=category.toLowerCase().trim();if(VALID_CATEGORIES3.includes(normalized))return normalized;return null}function validateMinScore(score){if(typeof score==="number"&&!Number.isNaN(score))return Math.max(0,Math.min(1,score));if(typeof score==="string"){let parsed=Number.parseFloat(score);if(!Number.isNaN(parsed))return Math.max(0,Math.min(1,parsed))}return null}function validateLimit(limit){if(typeof limit==="number"&&!Number.isNaN(limit)&&limit>0)return Math.min(limit,100);if(typeof limit==="string"){let parsed=Number.parseInt(limit,10);if(!Number.isNaN(parsed)&&parsed>0)return Math.min(parsed,100)}return DEFAULT_LIMIT}async function readSwarmKnowledge(directory){let swarmPath3=resolveSwarmKnowledgePath(directory);if(!existsSync145(swarmPath3))return[];return readKnowledge(swarmPath3)}async function readHiveKnowledge(){let hivePath=resolveHiveKnowledgePath2();if(!existsSync145(hivePath))return[];return readKnowledge(hivePath)}function filterSwarmEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize6(entry.lesson)))return!1;return!0})}function filterHiveEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize6(entry.lesson)))return!1;return!0})}function truncateLesson3(lesson,maxLength){if(lesson.length<=maxLength)return lesson;return`${lesson.slice(0,maxLength-3)}...`}function formatSwarmEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} phase(s)`),lines.push(` Project: ${entry.project_name}`),lines.join(`
|
|
6731
|
+
${scanResult.neutralized}`;return result}catch(error93){if(error93 instanceof DOMException&&(error93.name==="TimeoutError"||error93.name==="AbortError")){if(attempt>=GITINGEST_MAX_RETRIES)throw Error("gitingest request timed out");let backoff=200*2**attempt;await delay3(backoff);continue}if(error93 instanceof Error&&error93.message.startsWith("gitingest "))throw error93;if(attempt<GITINGEST_MAX_RETRIES){let backoff=200*2**attempt;await delay3(backoff);continue}throw error93}throw Error("gitingest request failed after retries")}var gitingest=createSwarmTool({description:"Fetch a GitHub repository's full content via gitingest.com. Returns summary, directory tree, and file contents optimized for LLM analysis. Use when you need to understand an external repository's structure or code.",args:{url:exports_external.string().describe("GitHub repository URL (e.g., https://github.com/owner/repo)"),maxFileSize:exports_external.number().optional().describe("Maximum file size in bytes to include (default: 50000)"),pattern:exports_external.string().optional().describe("Glob pattern to filter files (e.g., '*.ts' or 'src/**/*.py')"),patternType:exports_external.enum(["include","exclude"]).optional().describe("Whether pattern includes or excludes matching files (default: exclude)")},async execute(args2,_directory,_ctx){return fetchGitingest(args2)}});init_zod();init_create_tool();init_path_security();import*as fs161 from"node:fs";import*as path274 from"node:path";var MAX_FILE_PATH_LENGTH2=500,MAX_SYMBOL_LENGTH=256,MAX_FILE_SIZE_BYTES7=1048576,MAX_CONSUMERS=100,SUPPORTED_EXTENSIONS2=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],BINARY_SIGNATURES2=[0,2303741511,4292411360,1195984440,626017350,1347093252],BINARY_PREFIX_BYTES2=4,BINARY_NULL_CHECK_BYTES2=8192,BINARY_NULL_THRESHOLD2=0.1;function validateFileInput(file3){if(!file3||file3.length===0)return"file is required";if(file3.length>MAX_FILE_PATH_LENGTH2)return`file exceeds maximum length of ${MAX_FILE_PATH_LENGTH2}`;if(containsControlChars(file3))return"file contains control characters";if(containsPathTraversal(file3))return"file contains path traversal";return null}function validateSymbolInput(symbol3){if(symbol3===void 0||symbol3==="")return null;if(symbol3.length>MAX_SYMBOL_LENGTH)return`symbol exceeds maximum length of ${MAX_SYMBOL_LENGTH}`;if(containsControlChars(symbol3))return"symbol contains control characters";if(containsPathTraversal(symbol3))return"symbol contains path traversal";return null}function isBinaryFile3(filePath,buffer){let ext=path274.extname(filePath).toLowerCase();if(ext===".json"||ext===".md"||ext===".txt")return!1;if(buffer.length>=BINARY_PREFIX_BYTES2){let uint323=buffer.subarray(0,BINARY_PREFIX_BYTES2).readUInt32BE(0);for(let sig of BINARY_SIGNATURES2)if(uint323===sig)return!0}let nullCount=0,checkLen=Math.min(buffer.length,BINARY_NULL_CHECK_BYTES2);for(let i=0;i<checkLen;i++)if(buffer[i]===0)nullCount++;return nullCount>checkLen*BINARY_NULL_THRESHOLD2}function parseImports(content,targetFile,targetSymbol){let imports=[],_resolvedTarget;try{_resolvedTarget=path274.resolve(targetFile)}catch{_resolvedTarget=targetFile}let targetBasename=path274.basename(targetFile,path274.extname(targetFile)),targetWithExt=targetFile,targetWithoutExt=targetFile.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,""),normalizedTargetWithExt=path274.normalize(targetWithExt).replace(/\\/g,"/"),normalizedTargetWithoutExt=path274.normalize(targetWithoutExt).replace(/\\/g,"/"),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`]+)['"`]|import\s+['"`]([^'"`]+)['"`]|require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let modulePath=match[1]||match[2]||match[3];if(!modulePath)continue;let lineNum=(content.substring(0,match.index).match(/\n/g)||[]).length+1,matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";let _normalizedModule=modulePath.replace(/^\.\//,"").replace(/^\.\.\\/,"../"),isMatch=!1,_targetDir=path274.dirname(targetFile),targetExt=path274.extname(targetFile),targetBasenameNoExt=path274.basename(targetFile,targetExt),moduleNormalized=modulePath.replace(/\\/g,"/").replace(/^\.\//,""),moduleName=modulePath.split(/[/\\]/).pop()||"",moduleNameNoExt=moduleName.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/i,"");if(modulePath===targetBasename||modulePath===targetBasenameNoExt||modulePath===`./${targetBasename}`||modulePath===`./${targetBasenameNoExt}`||modulePath===`../${targetBasename}`||modulePath===`../${targetBasenameNoExt}`||moduleNormalized===normalizedTargetWithExt||moduleNormalized===normalizedTargetWithoutExt||modulePath.endsWith(`/${targetBasename}`)||modulePath.endsWith(`\\${targetBasename}`)||modulePath.endsWith(`/${targetBasenameNoExt}`)||modulePath.endsWith(`\\${targetBasenameNoExt}`)||moduleNameNoExt===targetBasenameNoExt||`./${moduleNameNoExt}`===targetBasenameNoExt||moduleName===targetBasename||moduleName===targetBasenameNoExt)isMatch=!0;if(isMatch&&targetSymbol)if(importType==="namespace"||importType==="sideeffect")isMatch=!1;else{let namedMatch=matchedString.match(/import\s+\{([\s\S]*?)\}\s+from/);if(namedMatch)isMatch=namedMatch[1].split(",").map((s)=>{let parts=s.trim().split(/\s+as\s+/i),originalName=parts[0].trim(),aliasName=parts[1]?.trim();return{original:originalName,alias:aliasName}}).some(({original,alias})=>original===targetSymbol||alias===targetSymbol);else if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from/m);if(defaultMatch)isMatch=defaultMatch[1]===targetSymbol}}if(isMatch)imports.push({line:lineNum,imports:modulePath,importType,raw:matchedString.trim()})}return imports}var SKIP_DIRECTORIES4=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg"]);function findSourceFiles2(dir,files=[],stats2={skippedDirs:[],skippedFiles:0,fileErrors:[]}){let entries;try{entries=fs161.readdirSync(dir)}catch(e){return stats2.fileErrors.push({path:dir,reason:e instanceof Error?e.message:"readdir failed"}),files}entries.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries){if(SKIP_DIRECTORIES4.has(entry)){stats2.skippedDirs.push(path274.join(dir,entry));continue}let fullPath=path274.join(dir,entry),stat21;try{stat21=fs161.statSync(fullPath)}catch(e){stats2.fileErrors.push({path:fullPath,reason:e instanceof Error?e.message:"stat failed"});continue}if(stat21.isDirectory())findSourceFiles2(fullPath,files,stats2);else if(stat21.isFile()){let ext=path274.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS2.includes(ext))files.push(fullPath)}}return files}var imports=createSwarmTool({description:"Find all reverse dependencies (consumers) that import from a given file. Returns JSON with file path, line numbers, and import metadata for each consumer. Use this to understand who depends on a module before refactoring.",args:{file:exports_external.string().describe('Source file path to find importers for (e.g., "./src/utils.ts")'),symbol:exports_external.string().optional().describe('Optional specific symbol to filter imports (e.g., "MyClass")')},async execute(args2,_directory,_ctx){let typedArgs=args2,file3,symbol3;try{if(typedArgs&&typeof typedArgs==="object")file3=typedArgs.file,symbol3=typedArgs.symbol}catch{}if(file3===void 0)return JSON.stringify({error:"invalid arguments: file is required",target:"",symbol:void 0,consumers:[],count:0},null,2);let fileValidationError=validateFileInput(file3);if(fileValidationError){let errorResult={error:`invalid file: ${fileValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}let symbolValidationError=validateSymbolInput(symbol3);if(symbolValidationError){let errorResult={error:`invalid symbol: ${symbolValidationError}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}try{let targetFile=path274.resolve(file3);if(!fs161.existsSync(targetFile)){let errorResult={error:`target file not found: ${file3}`,target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}if(!fs161.statSync(targetFile).isFile())return JSON.stringify({error:"target must be a file, not a directory",target:file3,symbol:symbol3,consumers:[],count:0},null,2);let baseDir=path274.dirname(targetFile),filesToScan=findSourceFiles2(baseDir,[],{skippedDirs:[],skippedFiles:0,fileErrors:[]}).filter((f)=>f!==targetFile).sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())).slice(0,MAX_CONSUMERS*10),consumers=[],skippedFileCount=0,totalMatchesFound=0;for(let filePath of filesToScan){if(consumers.length>=MAX_CONSUMERS)break;try{if(fs161.statSync(filePath).size>MAX_FILE_SIZE_BYTES7){skippedFileCount++;continue}let buffer=fs161.readFileSync(filePath);if(isBinaryFile3(filePath,buffer)){skippedFileCount++;continue}let content=buffer.toString("utf-8"),fileImports=parseImports(content,targetFile,symbol3);for(let imp of fileImports){if(totalMatchesFound++,consumers.length>=MAX_CONSUMERS)continue;if(consumers.some((c)=>c.file===filePath&&c.line===imp.line))continue;consumers.push({file:filePath,line:imp.line,imports:imp.imports,importType:imp.importType,raw:imp.raw})}}catch(_e){skippedFileCount++}}let result={target:file3,symbol:symbol3,consumers,count:consumers.length},parts=[];if(filesToScan.length>=MAX_CONSUMERS*10)parts.push(`Scanned ${filesToScan.length} files`);if(skippedFileCount>0)parts.push(`${skippedFileCount} skipped (size/binary/errors)`);if(consumers.length>=MAX_CONSUMERS){let hidden=totalMatchesFound-consumers.length;if(hidden>0)parts.push(`Results limited to ${MAX_CONSUMERS} consumers (${hidden} hidden)`);else parts.push(`Results limited to ${MAX_CONSUMERS} consumers`)}if(parts.length>0)result.message=`${parts.join("; ")}.`;return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`scan failed: ${e.message||"internal error"}`:"scan failed: unknown error",target:file3,symbol:symbol3,consumers:[],count:0};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_types();init_knowledge_validator();init_cohort_identity();init_worktree_identity();init_manager();init_create_tool();import{randomUUID as randomUUID33}from"node:crypto";var VALID_CATEGORIES2=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],KNOWLEDGE_ADD_FIELD_CAP=20;function mergeLessonTags(tagsInput,lesson){return dedupeCapped([...Array.isArray(tagsInput)?tagsInput:[],...inferTags(lesson)],{cap:KNOWLEDGE_ADD_FIELD_CAP})}function strArray(v){return Array.isArray(v)?dedupeCapped(v,{cap:KNOWLEDGE_ADD_FIELD_CAP}):void 0}var knowledge_add=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Store a new lesson in the knowledge base for future reference. The lesson will be available for retrieval via knowledge_recall.",args:{lesson:exports_external.string().min(15).max(280).describe("The lesson to store (15-280 characters)"),category:exports_external.enum(VALID_CATEGORIES2).describe("Knowledge category for the lesson"),tags:exports_external.array(exports_external.string()).optional().describe("Optional tags for better searchability"),scope:exports_external.string().optional().describe("Scope of the lesson (global or stack:<name>)"),applies_to_agents:exports_external.array(exports_external.string()).optional().describe('Agent roles this lesson applies to (e.g. ["coder"]). REQUIRED (or applies_to_tools) for the lesson to become active.'),applies_to_tools:exports_external.array(exports_external.string()).optional().describe('Tool names this lesson applies to (e.g. ["edit","bash"]). REQUIRED (or applies_to_agents) for the lesson to become active.'),required_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to always take. At least one predicate field (required_actions / forbidden_actions / verification_checks) is REQUIRED for the lesson to become active."),forbidden_actions:exports_external.array(exports_external.string()).optional().describe("Concrete actions to never take."),verification_checks:exports_external.array(exports_external.string()).optional().describe("Checks a reviewer can run to verify compliance.")},execute:async(args2,directory)=>{let lessonInput,categoryInput,tagsInput,scopeInput;try{if(args2&&typeof args2==="object"){let obj2=args2;lessonInput=obj2.lesson,categoryInput=obj2.category,tagsInput=obj2.tags,scopeInput=obj2.scope}}catch{}if(typeof lessonInput!=="string")return JSON.stringify({success:!1,error:"lesson must be a string"});let lesson=lessonInput;if(lesson.length<15||lesson.length>280)return JSON.stringify({success:!1,error:"lesson must be between 15 and 280 characters"});if(typeof categoryInput!=="string")return JSON.stringify({success:!1,error:"category must be a string"});let category=categoryInput;if(!VALID_CATEGORIES2.includes(category))return JSON.stringify({success:!1,error:`category must be one of: ${VALID_CATEGORIES2.join(", ")}`});let tags=mergeLessonTags(tagsInput,lesson),scope=typeof scopeInput==="string"&&scopeInput.length>0?scopeInput:"global",obj=args2&&typeof args2==="object"?args2:{},actionable={applies_to_agents:strArray(obj.applies_to_agents),applies_to_tools:strArray(obj.applies_to_tools),required_actions:strArray(obj.required_actions),forbidden_actions:strArray(obj.forbidden_actions),verification_checks:strArray(obj.verification_checks)},shape=validateActionableFields(actionable);if(!shape.valid)return JSON.stringify({success:!1,error:`invalid actionability fields: ${shape.errors.join("; ")}`});let project_name="",phase_number=1;try{let plan=await loadPlan(directory);if(project_name=plan?.title??"",typeof plan?.current_phase==="number")phase_number=plan.current_phase}catch{}let producer=null;try{let[worktreeId,cohort]=await Promise.all([resolveWorktreeId(directory),resolveCohortId(directory)]);producer={cohort_id:cohort.cohortId,worktree_id:worktreeId}}catch{}let nowIso2=new Date().toISOString(),entry={id:randomUUID33(),tier:"swarm",lesson,category,tags,scope,confidence:0.5,status:"candidate",confirmed_by:[],project_name,retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,producer,revision:1,content_hash:computeContentHash(lesson),created_at:nowIso2,updated_at:nowIso2,auto_generated:!1,hive_eligible:!1,...actionable},config3,dedupThreshold=0.6;try{if(config3=loadPluginConfigWithMeta(directory).config,dedupThreshold=config3.knowledge?.dedup_threshold??0.6,config3.knowledge?.validation_enabled!==!1){let validation2=validateLesson(lesson,[],{category,scope,confidence:0.5});if(!validation2.valid)return JSON.stringify({success:!1,error:`Validation failed: ${validation2.reason}`})}}catch{}let actionability=validateActionability(entry);if(!actionability.actionable){try{await appendUnactionable(directory,entry,actionability.reason??"unactionable")}catch{}return JSON.stringify({success:!1,quarantined:!0,id:entry.id,reason:actionability.reason,hint:"Provide at least one of required_actions/forbidden_actions/verification_checks AND at least one of applies_to_agents/applies_to_tools, then retry."})}try{let maxEntries=config3?.knowledge?.swarm_max_entries??100,duplicateResponse;if(await transactKnowledge(resolveSwarmKnowledgePath(directory),(existingEntries)=>{let activeDuplicate=findActiveSwarmNearDuplicate(lesson,existingEntries,dedupThreshold);if(activeDuplicate){let result=reinforceSwarmKnowledgeEntry(activeDuplicate,{phase_number,confirmed_at:new Date().toISOString(),project_name});return duplicateResponse={id:activeDuplicate.id,reinforced:result.reinforced,idempotent:result.reason==="already_confirmed_phase",inactive:!1},result.reinforced?existingEntries:null}let inactiveDuplicate=findNearDuplicate(lesson,existingEntries,dedupThreshold);if(inactiveDuplicate)return duplicateResponse={id:inactiveDuplicate.id,reinforced:!1,idempotent:!1,inactive:!0},null;let updated=[...existingEntries,entry];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated}),duplicateResponse){if(duplicateResponse.inactive)return JSON.stringify({success:!1,id:duplicateResponse.id,message:"near-duplicate of inactive existing entry"});return JSON.stringify({success:!0,id:duplicateResponse.id,reinforced:duplicateResponse.reinforced,idempotent:duplicateResponse.idempotent,message:duplicateResponse.reinforced?"near-duplicate reinforced existing entry":"near-duplicate already confirmed for this phase"})}}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}return JSON.stringify({success:!0,id:entry.id,category})}});init_zod();init_knowledge_store();init_knowledge_validator();init_skill_invalidator();init_curation_policy();init_logger();init_create_tool();var MODES2=["archive","quarantine","purge"],TIERS=["swarm","hive"];async function loadConfigForPolicy(directory){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),{config:loaded}=loadPluginConfigWithMeta2(directory);return KnowledgeConfigSchema2.parse(loaded.knowledge??{})}var knowledge_archive=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Archive (default), quarantine, or purge a swarm or hive knowledge entry by ID, appending an immutable audit tombstone. 'archive'/'quarantine' set the entry status reversibly and hide it from recall; 'purge' hard-deletes and requires allow_purge:true.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry"),tier:exports_external.enum(TIERS).optional().describe("Knowledge tier to modify; default 'swarm'"),reason:exports_external.string().min(1).max(500).describe("Why the entry is being archived/quarantined/purged"),evidence:exports_external.string().max(1000).optional().describe('Supporting evidence (e.g. "ignored 8 times, contradicted by tests")'),mode:exports_external.enum(MODES2).optional().describe("Default 'archive'"),allow_purge:exports_external.boolean().optional().describe("Admin flag required when mode='purge'")},execute:async(args2,directory,ctx)=>{let a=args2??{},id=typeof a.id==="string"?a.id:"";if(!id)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let reason=typeof a.reason==="string"?a.reason:"";if(!reason)return JSON.stringify({success:!1,error:"reason is required"});let evidence2=typeof a.evidence==="string"?a.evidence:void 0,tier=a.tier==="hive"?"hive":"swarm",mode=a.mode==="quarantine"||a.mode==="purge"?a.mode:"archive";if(mode==="purge"&&a.allow_purge!==!0)return JSON.stringify({success:!1,error:"purge requires allow_purge:true (admin flag)"});if(mode==="quarantine"){if(tier==="hive")return JSON.stringify({success:!1,error:"quarantine via the archive tool is swarm-only; use tier:'swarm' or the /swarm knowledge quarantine command"});try{let target=(await readKnowledge(resolveSwarmKnowledgePath(directory))).find((e)=>e.id===id);if(!target)return JSON.stringify({success:!1,message:"entry not found"});let reportedBy=ctx?.agent==="architect"?"architect":"user",curationInput={directory,action:"quarantine",entryId:id,reason,evidenceScope:"cohort-wide",actorRole:ctx?.agent},curationContext={config:await loadConfigForPolicy(directory),entry:target};await quarantineEntry(directory,id,reason,reportedBy,{input:curationInput,context:curationContext})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error during quarantine"})}return JSON.stringify({success:!0,id,tier,mode,status:"quarantined"})}let knowledgePath=tier==="hive"?resolveHiveKnowledgePath2():resolveSwarmKnowledgePath(directory),found=!1,previousStatus,now2=new Date().toISOString(),resultStatus,casExpectedRevision,casExpectedContentHash;if(tier==="swarm"){let preEntries;try{preEntries=await readKnowledge(knowledgePath)}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}let preTarget=preEntries.find((e)=>e.id===id)??null;if(preTarget){let curationInput={directory,action:mode,entryId:id,reason,evidenceScope:"cohort-wide",actorRole:ctx?.agent},curationContext={config:await loadConfigForPolicy(directory),entry:preTarget},decision=await authorizeCuration(curationInput,curationContext);if(!decision.authorized)return JSON.stringify({success:!1,error:`Cohort-safety policy blocked this ${mode}: ${decision.detail}`,basis:decision.basis});casExpectedRevision=preTarget.revision,casExpectedContentHash=preTarget.content_hash}}if(tier==="swarm"&&mode==="archive"){let casResult;try{casResult=await transactKnowledgeWithCas(directory,knowledgePath,id,casExpectedRevision,casExpectedContentHash,(entry)=>{if(found=!0,previousStatus=entry.status,entry.status==="archived")return resultStatus="archived",null;return resultStatus="archived",{mutated:{...entry,status:"archived",archived_from:entry.status,archived_at:now2,updated_at:now2}}})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(casResult.casFailed)return JSON.stringify({success:!1,error:"entry changed since authorization (revision/content-hash mismatch); stale archive plan rejected"})}else try{await transactKnowledge(knowledgePath,(entries)=>{let target=entries.find((e)=>e.id===id);if(!target)return null;if(found=!0,previousStatus=target.status,mode==="purge")return warn(`[knowledge_archive] PURGE: hard-deleting ${tier} entry id=${id} actor=${ctx?.agent??"unknown"} reason=${reason}`),resultStatus="purged",entries.filter((e)=>e.id!==id);if(target.status==="archived")return resultStatus="archived",entries;return resultStatus="archived",entries.map((e)=>e.id===id?{...e,status:"archived",archived_from:target.status,archived_at:now2,updated_at:now2}:e)})}catch(err){return JSON.stringify({success:!1,error:err instanceof Error?err.message:"Unknown error"})}if(!found)return JSON.stringify({success:!1,message:"entry not found"});return await writeArchiveTombstoneAndInvalidateSkills({directory,entryId:id,tier,actor:ctx?.agent??"unknown",reason,mode,evidence:evidence2,previousStatus,sourceLabel:"knowledge-archive"}),JSON.stringify({success:!0,id,tier,mode,previous_status:previousStatus,status:resultStatus})}});init_zod();init_config();init_knowledge_store();init_create_tool();import{existsSync as existsSync146}from"node:fs";var DEFAULT_LIMIT=10,MAX_LESSON_LENGTH=200,VALID_CATEGORIES3=["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"],VALID_STATUSES=["candidate","established","promoted","archived"],DEFAULT_QUERY_STATUSES=new Set(["established","promoted"]),VALID_TIERS=["swarm","hive","all"];function validateTierInput(tier){if(typeof tier!=="string")return null;let normalized=tier.toLowerCase().trim();if(VALID_TIERS.includes(normalized))return normalized;return null}function validateStatusInput(status){if(typeof status!=="string")return null;let normalized=status.toLowerCase().trim();if(VALID_STATUSES.includes(normalized))return normalized;return null}function validateCategoryInput(category){if(typeof category!=="string")return null;let normalized=category.toLowerCase().trim();if(VALID_CATEGORIES3.includes(normalized))return normalized;return null}function validateMinScore(score){if(typeof score==="number"&&!Number.isNaN(score))return Math.max(0,Math.min(1,score));if(typeof score==="string"){let parsed=Number.parseFloat(score);if(!Number.isNaN(parsed))return Math.max(0,Math.min(1,parsed))}return null}function validateLimit(limit){if(typeof limit==="number"&&!Number.isNaN(limit)&&limit>0)return Math.min(limit,100);if(typeof limit==="string"){let parsed=Number.parseInt(limit,10);if(!Number.isNaN(parsed)&&parsed>0)return Math.min(parsed,100)}return DEFAULT_LIMIT}async function readSwarmKnowledge(directory){let swarmPath3=resolveSwarmKnowledgePath(directory);if(!existsSync146(swarmPath3))return[];return readKnowledge(swarmPath3)}async function readHiveKnowledge(){let hivePath=resolveHiveKnowledgePath2();if(!existsSync146(hivePath))return[];return readKnowledge(hivePath)}function filterSwarmEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize6(entry.lesson)))return!1;return!0})}function filterHiveEntries(entries,filters,suppressedLessons,scopeFilter){return entries.filter((entry)=>{if(filters.status){if(entry.status!==filters.status)return!1}else if(!DEFAULT_QUERY_STATUSES.has(entry.status))return!1;if(filters.category&&entry.category!==filters.category)return!1;if(filters.minScore!==void 0&&entry.confidence<filters.minScore)return!1;if(scopeFilter&&scopeFilter.length>0){let entryScope=entry.scope??"global";if(!scopeFilter.some((pattern)=>entryScope===pattern))return!1}if(suppressedLessons.has(normalize6(entry.lesson)))return!1;return!0})}function truncateLesson3(lesson,maxLength){if(lesson.length<=maxLength)return lesson;return`${lesson.slice(0,maxLength-3)}...`}function formatSwarmEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} phase(s)`),lines.push(` Project: ${entry.project_name}`),lines.join(`
|
|
6731
6732
|
`)}function formatHiveEntry(entry){let lines=[];return lines.push(`[${entry.tier.toUpperCase()}] ${entry.id}`),lines.push(` Lesson: ${truncateLesson3(entry.lesson,MAX_LESSON_LENGTH)}`),lines.push(` Category: ${entry.category}`),lines.push(` Status: ${entry.status}`),lines.push(` Confidence: ${entry.confidence.toFixed(2)}`),lines.push(` Encounter Score: ${entry.encounter_score?.toFixed(2)??"N/A"}`),lines.push(` Source Project: ${entry.source_project}`),lines.push(` Confirmed by: ${entry.confirmed_by.length} project(s)`),lines.join(`
|
|
6732
6733
|
`)}var knowledge_query=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs structured filter-based retrieval of swarm knowledge (project-level) or hive knowledge (cross-project). Returns formatted text for human inspection. This is the tool to use when the user knows the CATEGORY, STATUS, or SCORE they want to filter by. For semantic natural-language search, use `knowledge_recall` instead.",args:{tier:exports_external.string().optional().describe("Knowledge tier to query: 'swarm', 'hive', or 'all' (default: 'all')"),status:exports_external.string().optional().describe("Filter by status: 'candidate', 'established', 'promoted', or 'archived'"),category:exports_external.string().optional().describe("Filter by category: 'process', 'architecture', 'tooling', 'security', 'testing', 'debugging', 'performance', 'integration', 'todo', or 'other'"),min_score:exports_external.number().optional().describe("Minimum confidence score filter (0.0-1.0)"),limit:exports_external.number().optional().describe(`Maximum number of results to return (default: ${DEFAULT_LIMIT}, max: 100)`)},async execute(args2,directory){let tierInput,statusInput,categoryInput,minScoreInput,limitInput;try{if(args2&&typeof args2==="object"){let obj=args2;tierInput=obj.tier,statusInput=obj.status,categoryInput=obj.category,minScoreInput=obj.min_score,limitInput=obj.limit}}catch{}let tier=validateTierInput(tierInput)??"all",status=validateStatusInput(statusInput)??null,category=validateCategoryInput(categoryInput)??null,minScore=validateMinScore(minScoreInput)??null,limit=validateLimit(limitInput),filters={status:status??void 0,category:category??void 0,minScore:minScore??void 0},retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),results=[],scopeFilter;try{let{config:config3}=loadPluginConfigWithMeta(directory);scopeFilter=config3.knowledge?.scope_filter}catch{}if(tier==="swarm"||tier==="all"){let swarmEntries=await readSwarmKnowledge(directory),filtered=filterSwarmEntries(swarmEntries,filters,suppressedLessons,scopeFilter);for(let entry of filtered)results.push({entry,tier:"swarm"})}if(tier==="hive"||tier==="all"){let hiveEntries=await readHiveKnowledge(),filtered=filterHiveEntries(hiveEntries,filters,suppressedLessons,scopeFilter);for(let entry of filtered)results.push({entry,tier:"hive"})}let limitedResults=results.slice(0,limit);if(limitedResults.length===0){let tierDesc=tier==="all"?"swarm or hive":tier,filterParts=[];if(status)filterParts.push(`status=${status}`);if(category)filterParts.push(`category=${category}`);if(minScore!==null)filterParts.push(`min_score=${minScore}`);let filterDesc=filterParts.length>0?` with filters: ${filterParts.join(", ")}`:"";return`No knowledge entries found for tier '${tierDesc}'${filterDesc}.`}let outputLines=[];outputLines.push(`=== Knowledge Query Results (${limitedResults.length} of ${results.length} shown) ===`),outputLines.push("");for(let{entry,tier:entryTier}of limitedResults){if(entryTier==="hive")outputLines.push(formatHiveEntry(entry));else outputLines.push(formatSwarmEntry(entry));outputLines.push("")}if(outputLines.push("---"),outputLines.push(`Total matched: ${results.length} | Tier: ${tier} | Limit: ${limit}`),status)outputLines.push(`Status filter: ${status}`);if(category)outputLines.push(`Category filter: ${category}`);if(minScore!==null)outputLines.push(`Min score filter: ${minScore}`);return outputLines.join(`
|
|
6733
6734
|
`)}});init_knowledge_recall();init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_link();init_promotion_evidence_store();init_logger();init_create_tool();async function readLinkPointerSafe(directory){try{return readLinkPointer(directory)?.linkId}catch{return}}var IGNORE_REASONS=["stale","superseded","unsafe","too_generic","already_satisfied","other"],PROPOSED_ACTIONS=["archive","revise","quarantine"],VERIFIED_BY=["reviewer","test_engineer","architect"],appliedItem=exports_external.object({id:exports_external.string().min(1),how:exports_external.string().min(1).max(500),evidence_files:exports_external.array(exports_external.string()).optional(),evidence_commands:exports_external.array(exports_external.string()).optional(),verified_by:exports_external.enum(VERIFIED_BY).optional()}),ignoredItem=exports_external.object({id:exports_external.string().min(1),reason:exports_external.enum(IGNORE_REASONS),note:exports_external.string().max(500).optional()}),notApplicableItem=exports_external.object({id:exports_external.string().min(1),reason:exports_external.string().trim().min(1).max(500)}),contradictedItem=exports_external.object({id:exports_external.string().min(1),evidence:exports_external.string().min(1).max(500),proposed_action:exports_external.enum(PROPOSED_ACTIONS)}),newLessonItem=exports_external.object({lesson:exports_external.string().min(15).max(280),category:exports_external.string().min(1),evidence:exports_external.string().max(500).optional(),applies_to_agents:exports_external.array(exports_external.string()).optional(),applies_to_tools:exports_external.array(exports_external.string()).optional(),required_actions:exports_external.array(exports_external.string()).optional(),forbidden_actions:exports_external.array(exports_external.string()).optional(),verification_checks:exports_external.array(exports_external.string()).optional()});function receiptSourceForAgent(agent){let base=stripKnownSwarmPrefix(agent.trim());if(!base||base==="unknown")return"unknown";if(base==="reviewer")return"reviewer";if(base==="test_engineer")return"test_engineer";if(base==="architect")return"architect";return"delegate"}var knowledge_receipt=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"File a receipt for knowledge surfaced by a retrieval (by trace_id): which entries were applied (with evidence), ignored with a reason (relevant but deliberately not followed — counts against the entry), marked n_a with a reason (not applicable to this task — neutral), or contradicted (with proposed remediation), plus any new lessons. Each item is recorded as an immutable knowledge event. Set no_relevant_knowledge:true when a retrieval surfaced nothing useful.",args:{trace_id:exports_external.string().min(1).describe("trace_id from a prior knowledge_recall/injection, or 'none' if no retrieval occurred"),task_id:exports_external.string().min(1).optional(),phase:exports_external.string().optional(),applied:exports_external.array(appliedItem).optional(),ignored:exports_external.array(ignoredItem).optional().describe("entries you judged relevant but deliberately did not follow (counts against the entry). NOT for not-applicable entries — file those under n_a"),n_a:exports_external.array(notApplicableItem).optional().describe("entries that did not apply to this task (neutral; reasoned). Replaces the removed not_relevant ignore reason"),contradicted:exports_external.array(contradictedItem).optional(),new_lessons:exports_external.array(newLessonItem).optional(),no_relevant_knowledge:exports_external.boolean().optional()},execute:async(args2,directory,ctx)=>{let a=args2??{},traceId=typeof a.trace_id==="string"?a.trace_id:"";if(!traceId)return JSON.stringify({recorded:!1,error:'trace_id is required (use "none" if no retrieval occurred)'});let taskId=typeof a.task_id==="string"&&a.task_id.trim()?a.task_id.trim():void 0,phase=typeof a.phase==="string"?a.phase:void 0,applied=Array.isArray(a.applied)?a.applied:[],ignored=Array.isArray(a.ignored)?a.ignored:[],notApplicable=Array.isArray(a.n_a)?a.n_a:[],contradicted=Array.isArray(a.contradicted)?a.contradicted:[],newLessons=Array.isArray(a.new_lessons)?a.new_lessons:[],noRelevant=a.no_relevant_knowledge===!0;if(applied.length===0&&ignored.length===0&¬Applicable.length===0&&contradicted.length===0&&newLessons.length===0&&!noRelevant)return JSON.stringify({recorded:!1,error:"empty receipt: provide at least one applied/ignored/n_a/contradicted entry, a new lesson, or set no_relevant_knowledge:true"});let sessionId=ctx?.sessionID??"unknown",agent=ctx?.agent??"unknown",receiptSource=receiptSourceForAgent(agent),knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let base={trace_id:traceId,session_id:sessionId,phase,task_id:taskId,agent,source:receiptSource},recordedEventIds=[],diagnosticEventIds=[],emit3=async(event)=>{let id=(await recordKnowledgeEvent(directory,event))?.event_id??"";if(id)diagnosticEventIds.push(id);return id},eventIdByKnowledgeId=new Map,validationItems=[...applied.map((i)=>({id:i.id,outcome:"applied",reason:i.how})),...ignored.map((i)=>({id:i.id,outcome:"ignored",reason:i.note?`${i.reason}: ${i.note}`:i.reason})),...notApplicable.map((i)=>({id:i.id,outcome:"n_a",reason:i.reason})),...contradicted.map((i)=>({id:i.id,outcome:"contradicted",reason:`${i.proposed_action}: ${i.evidence}`}))],needsValidation=validationItems.length>0||noRelevant,acceptedIds=new Set,closesNoRelevant=!1,acceptedItems=[],authoritativeEventIds={},cohortId,linkId;if(needsValidation){try{cohortId=await ensureCohortIdCached(directory,sessionId),linkId=await readLinkPointerSafe(directory)}catch{}let validation2=await validateReceipt({directory,trace_id:traceId,session_id:sessionId,task_id:taskId,phase,agent,source:receiptSource,cohort_id:cohortId,source_link_id:linkId,items:validationItems,no_relevant_knowledge:noRelevant,grace_days:knowledgeConfig.receipt_close_grace_days});if(!validation2.ok)return JSON.stringify({recorded:!1,rejected:!0,reason:validation2.reason,detail:validation2.detail,rejected_items:validation2.rejected_items});if(acceptedIds=new Set(validation2.accepted.map((i)=>i.id)),closesNoRelevant=validation2.closes_no_relevant,acceptedItems=validation2.accepted,authoritativeEventIds=validation2.authoritative_event_ids,recordedEventIds.push(...Object.values(authoritativeEventIds)),validation2.no_relevant_event_id)recordedEventIds.push(validation2.no_relevant_event_id)}if(closesNoRelevant)await emit3({type:"no_relevant",...base,reason:"no relevant knowledge surfaced by the trace"});for(let item of applied){if(!acceptedIds.has(item.id))continue;await emit3({type:"applied",...base,knowledge_id:item.id,reason:item.how,evidence:{files:item.evidence_files,commands:item.evidence_commands,summary:item.verified_by?`verified_by=${item.verified_by}`:void 0}});let eid=authoritativeEventIds[item.id];if(eid)eventIdByKnowledgeId.set(item.id,eid)}for(let item of ignored){if(!acceptedIds.has(item.id))continue;await emit3({type:"ignored",...base,knowledge_id:item.id,reason:item.note?`${item.reason}: ${item.note}`:item.reason})}for(let item of notApplicable){if(!acceptedIds.has(item.id))continue;await emit3({type:"n_a",...base,knowledge_id:item.id,reason:item.reason})}for(let item of contradicted){if(!acceptedIds.has(item.id))continue;await emit3({type:"contradicted",...base,knowledge_id:item.id,reason:`${item.proposed_action}: ${item.evidence}`,evidence:{summary:item.evidence}});let eid=authoritativeEventIds[item.id];if(eid)eventIdByKnowledgeId.set(item.id,eid)}if(acceptedItems.length>0)try{let now2=new Date().toISOString(),evidenceRecords=[];for(let item of acceptedItems){if(item.outcome!=="applied"&&item.outcome!=="contradicted")continue;let receiptEventId=eventIdByKnowledgeId.get(item.id);if(!cohortId||!receiptEventId)continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:item.id,retrieval_trace_id:traceId,receipt_outcome:item.outcome==="applied"?"applied":"contradicted",receipt_source:receiptSource,receipt_event_id:receiptEventId,phase,timestamp:now2})}await appendPromotionEvidence(directory,evidenceRecords)}catch{}let newLessonResults=[];for(let item of newLessons){let raw=await knowledge_add.execute({lesson:item.lesson,category:item.category,applies_to_agents:item.applies_to_agents,applies_to_tools:item.applies_to_tools,required_actions:item.required_actions,forbidden_actions:item.forbidden_actions,verification_checks:item.verification_checks},ctx);try{let output=typeof raw==="string"?raw:typeof raw==="object"&&raw!==null&&("output"in raw)&&typeof raw.output==="string"?raw.output:"";newLessonResults.push(JSON.parse(output))}catch{newLessonResults.push({success:!1})}}return log("[knowledge_receipt] completed",{agent,source:receiptSource,session_id:sessionId,trace_id:traceId,applied:applied.length,ignored:ignored.length,n_a:notApplicable.length,contradicted:contradicted.length,new_lessons:newLessonResults.length,no_relevant_knowledge:noRelevant,event_count:recordedEventIds.length,diagnostic_event_count:diagnosticEventIds.length}),JSON.stringify({recorded:!0,trace_id:traceId,applied:applied.length,ignored:ignored.length,n_a:notApplicable.length,contradicted:contradicted.length,new_lessons:newLessonResults,no_relevant_knowledge:noRelevant,event_ids:recordedEventIds})}});init_zod();init_knowledge_store();init_skill_invalidator();init_curation_policy();init_create_tool();async function loadConfigForPolicy2(directory){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema));try{let{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),{config:loadedConfig}=loadPluginConfigWithMeta2(directory);return KnowledgeConfigSchema2.parse(loadedConfig.knowledge??{})}catch{return KnowledgeConfigSchema2.parse({})}}var _internals219={transactKnowledge,writeArchiveTombstoneAndInvalidateSkills},knowledge_remove=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Delete an outdated swarm knowledge entry by ID (swarm tier only — does not affect hive). Promoted entries cannot be deleted. Double-deletion is idempotent — removing a non-existent entry returns a clear message without error.",args:{id:exports_external.string().min(1).describe("UUID of the knowledge entry to remove")},execute:async(args2,directory)=>{let idInput;try{if(args2&&typeof args2==="object")idInput=args2.id}catch{}if(typeof idInput!=="string"||idInput.length<1)return JSON.stringify({success:!1,error:"id must be a non-empty string"});let id=idInput,swarmPath3=resolveSwarmKnowledgePath(directory),preEntries;try{preEntries=await readKnowledge(swarmPath3)}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}let preTarget=preEntries.find((e)=>e.id===id)??null;if(preTarget){let curationInput={directory,action:"remove",entryId:id,reason:"hard-delete via knowledge_remove tool",evidenceScope:"cohort-wide"},curationContext={config:await loadConfigForPolicy2(directory),entry:preTarget},decision=await authorizeCuration(curationInput,curationContext);if(!decision.authorized)return JSON.stringify({success:!1,error:`Cohort-safety policy blocked removal: ${decision.detail}`,basis:decision.basis})}let found=!1,remaining=0,isPromoted=!1;try{await _internals219.transactKnowledge(swarmPath3,(entries)=>{let entryToDelete=entries.find((entry)=>entry.id===id);if(!entryToDelete)return null;if(entryToDelete.status==="promoted")return isPromoted=!0,null;let filtered=entries.filter((entry)=>entry.id!==id);if(filtered.length===entries.length)return null;return found=!0,remaining=filtered.length,filtered})}catch(err){let message=err instanceof Error?err.message:"Unknown error";return JSON.stringify({success:!1,error:message})}if(isPromoted)return JSON.stringify({success:!1,message:"cannot delete promoted entry — this entry has been promoted to cross-project consensus"});if(!found)return JSON.stringify({success:!1,message:"entry not found"});return await _internals219.writeArchiveTombstoneAndInvalidateSkills({directory,entryId:id,tier:"swarm",actor:"knowledge_remove",reason:"hard-delete via knowledge_remove tool",mode:"purge",skipTombstone:!0,sourceLabel:"knowledge-remove"}),JSON.stringify({success:!0,removed:1,remaining})}});init_zod();init_file_locks();init_create_tool();async function executeLeanTurboAcquireLocks(args2){let{directory,laneId,files,agent,taskId,sessionID}=args2;try{let result=await acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID);if(result.acquired)return{success:!0,locks:result.locks};else return{success:!1,conflicts:result.conflicts}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_acquire_locks=createSwarmTool({description:"Acquire file locks for all files in a lane (all-or-nothing). Wraps acquireLaneLocks from src/parallel/file-locks. If any file is already locked, releases all previously acquired locks.",args:{directory:exports_external.string().describe("Project root directory"),laneId:exports_external.string().describe('Unique lane identifier (e.g., "lane-1")'),files:exports_external.array(exports_external.string().min(1)).min(1).describe("Array of file paths to lock"),agent:exports_external.string().describe("Agent name acquiring the locks"),taskId:exports_external.string().describe('Task ID (e.g., "4.1")'),sessionID:exports_external.string().describe("Session ID for the Lean Turbo run")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboAcquireLocks({...args2,directory:_directory}),null,2)}});init_zod();init_constants();import*as fs162 from"node:fs";import*as path275 from"node:path";init_create_tool();function readPlanJson2(directory){let planPath=path275.join(directory,".swarm","plan.json");if(!fs162.existsSync(planPath))return null;try{return JSON.parse(fs162.readFileSync(planPath,"utf-8"))}catch{return null}}async function executeLeanTurboPlanLanes(args2){let{directory,phase,scopes}=args2,plan=readPlanJson2(directory);if(!plan)return{success:!1,errors:["plan.json not found in .swarm directory"]};let defaultConfig={...DEFAULT_LEAN_TURBO_CONFIG};try{let lanePlan=planLeanTurboLanes(directory,phase,plan,defaultConfig,scopes);return{success:!0,plan:lanePlan,lanes:lanePlan.lanes,degradedTasks:lanePlan.degradedTasks,serializedTasks:lanePlan.serializedTasks}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_plan_lanes=createSwarmTool({description:"Partition phase tasks into parallel lanes based on file-scope conflicts. Wraps planLeanTurboLanes for Lean Turbo lane planning.",args:{directory:exports_external.string().describe("Project root directory where .swarm/plan.json is located"),phase:exports_external.number().int().positive().describe("Phase number to plan"),scopes:exports_external.record(exports_external.string(),exports_external.array(exports_external.string())).optional().describe("Optional pre-loaded scopes map (taskId -> file paths)")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboPlanLanes({...args2,directory:_directory}),null,2)}});init_zod();init_state4();init_create_tool();async function executeLeanTurboRunnerStatus(args2){let{directory,sessionID}=args2;try{let runState=loadLeanTurboRunState(directory,sessionID);if(!runState)return{success:!1,errors:["No Lean Turbo run state found for this session"]};return{success:!0,status:runState.status,phase:runState.phase,lanes:runState.lanes,degradedTasks:runState.degradedTasks,maxParallelCoders:runState.maxParallelCoders,sessionID:runState.sessionID,strategy:runState.strategy}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_runner_status=createSwarmTool({description:"Read Lean Turbo run state from .swarm/turbo-state.json. Returns status, phase, lanes, degraded tasks, and max parallel coders.",args:{directory:exports_external.string().describe("Project root directory where .swarm/turbo-state.json is located"),sessionID:exports_external.string().describe("Session ID for the Lean Turbo run")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboRunnerStatus({...args2,directory:_directory}),null,2)}});init_zod();init_constants();init_state4();init_create_tool();async function executeLeanTurboStatus(args2){let{directory,sessionID}=args2;try{let runState=loadLeanTurboRunState(directory,sessionID),defaultConfig={max_parallel_coders:DEFAULT_LEAN_TURBO_CONFIG.max_parallel_coders,require_declared_scope:DEFAULT_LEAN_TURBO_CONFIG.require_declared_scope,degrade_on_risk:DEFAULT_LEAN_TURBO_CONFIG.degrade_on_risk,conflict_policy:DEFAULT_LEAN_TURBO_CONFIG.conflict_policy};if(runState)return{success:!0,strategy:"lean",leanActive:runState.status==="running",config:defaultConfig,status:runState.status,phase:runState.phase,lanes:runState.lanes.length,degradedTasks:runState.degradedTasks.length};return{success:!0,strategy:"lean",leanActive:!1,config:defaultConfig,status:"idle",phase:void 0,lanes:0,degradedTasks:0}}catch(error93){return{success:!1,errors:[error93 instanceof Error?error93.message:String(error93)]}}}var lean_turbo_status=createSwarmTool({description:"Returns Lean Turbo configuration and active status for the current session. Shows whether lean turbo is active, current status, and configuration values.",args:{directory:exports_external.string().describe("Project root directory"),sessionID:exports_external.string().describe("Session ID to check status for")},execute:async(args2,_directory)=>{return JSON.stringify(await executeLeanTurboStatus({...args2,directory:_directory}),null,2)}});init_lint();init_spec_schema();init_effective_spec();init_create_tool();var OBLIGATION_KEYWORDS=["MUST","SHALL","SHOULD","MAY"],FR_ID_PATTERN2=/\bFR-(?!000)\d{3}\b/,OBLIGATION_PATTERN2=/\b(MUST|SHALL|SHOULD|MAY)\b/g,SCENARIO_PATTERN=/^##\s+Scenario\s*:/gm,GIVEN_WHEN_THEN_PATTERN=/\b(Given|When|Then|And|But)[:\s]/gi;function countRequirementsByObligation(content){let counts={MUST:0,SHALL:0,SHOULD:0,MAY:0},lines=content.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"").split(`
|
|
6734
6735
|
`);for(let line of lines){if(!line.match(FR_ID_PATTERN2))continue;let matches=line.matchAll(OBLIGATION_PATTERN2);for(let match of matches){let keyword=match[1];if(OBLIGATION_KEYWORDS.includes(keyword))counts[keyword]++}}return counts}function countScenarios(content){let scenarioCount=0,scenarioMatches=content.match(SCENARIO_PATTERN);if(scenarioMatches)scenarioCount+=scenarioMatches.length;let givenWhenThenMatches=content.match(GIVEN_WHEN_THEN_PATTERN);if(givenWhenThenMatches&&givenWhenThenMatches.length>0){if(scenarioCount===0)scenarioCount=(content.match(/\bWhen\s+/gi)||[]).length}return scenarioCount}var lint_spec=createSwarmTool({description:"Reads .swarm/spec.md, lints markdown spec for FR-IDs, obligations, and structure, and returns requirement counts by obligation level, scenario count, and any errors or warnings found.",args:{},async execute(_args,directory){let errors5=[],warnings=[],spec=readEffectiveSpecSync(directory);if(!spec)return JSON.stringify({valid:!1,specMtime:null,requirementCount:{MUST:0,SHALL:0,SHOULD:0,MAY:0,total:0},scenarioCount:0,errors:["spec.md not found and no valid OpenSpec-compatible projection available"],warnings:[]},null,2);let{mtime:specMtime,content}=spec,contentValidation=validateSpecContent(content);if(!contentValidation.valid)for(let issue3 of contentValidation.issues)errors5.push(`Line ${issue3.line}: ${issue3.message}`);let obligationCounts=countRequirementsByObligation(content),totalRequirements=Object.values(obligationCounts).reduce((sum,count)=>sum+count,0),scenarioCount=countScenarios(content),result={valid:errors5.length===0,specMtime,requirementCount:{...obligationCounts,total:totalRequirements},scenarioCount,errors:errors5,warnings:[...warnings,...spec.warnings]};return JSON.stringify(result,null,2)}});init_zod();init_engine();import*as fs163 from"node:fs";import*as path276 from"node:path";var _internals220={evaluateMutationGate,buildTestImprovementPrompt,buildMessage};function evaluateMutationGate(report,passThreshold=0.8,warnThreshold=0.6){if(passThreshold<warnThreshold)throw Error(`Invalid thresholds: passThreshold (${passThreshold}) must be >= warnThreshold (${warnThreshold})`);let adjustedKillRate=report.adjustedKillRate,survivedMutants=report.results.filter((result)=>result.outcome==="survived"),verdict;if(adjustedKillRate>=passThreshold)verdict="pass";else if(adjustedKillRate>=warnThreshold)verdict="warn";else verdict="fail";let testImprovementPrompt=_internals220.buildTestImprovementPrompt(report,passThreshold,verdict),message=_internals220.buildMessage(verdict,adjustedKillRate,report.killed,report.totalMutants,report.equivalent,warnThreshold);return{verdict,killRate:report.killRate,adjustedKillRate,totalMutants:report.totalMutants,killed:report.killed,survived:report.survived,threshold:passThreshold,warnThreshold,message,survivedMutants,testImprovementPrompt}}function buildTestImprovementPrompt(report,passThreshold,verdict){if(verdict==="pass")return"";let lowKillRateFunctions=[];for(let[key,stats2]of report.perFunction)if(stats2.killRate<passThreshold){let lastColon=key.lastIndexOf(":");if(lastColon===-1)continue;let filePath=key.substring(0,lastColon),functionName=key.substring(lastColon+1);lowKillRateFunctions.push(` - ${functionName} in ${filePath}: ${Math.round(stats2.killRate*100)}% kill rate (${stats2.killed}/${stats2.total} killed)`)}if(lowKillRateFunctions.length===0)return"";return`The following functions have low mutation kill rates and need stronger tests:
|
|
6735
6736
|
`+lowKillRateFunctions.join(`
|
|
6736
6737
|
`)}function buildMessage(verdict,adjustedKillRate,killed,totalMutants,equivalent,warnThreshold){let killRatePercent=Math.round(adjustedKillRate*100),effectiveTotal=totalMutants-equivalent;switch(verdict){case"pass":return`Mutation gate PASSED: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed)`;case"warn":return`Mutation gate WARNING: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed). Test improvement recommended.`;case"fail":return`Mutation gate FAILED: ${killRatePercent}% kill rate (${killed}/${effectiveTotal} mutants killed). Below minimum threshold of ${Math.round(warnThreshold*100)}%.`}}init_create_tool();init_resolve_working_directory();var mutation_test=createSwarmTool({description:"Execute mutation testing with pre-generated patches — applies each mutant patch, runs tests, and evaluates kill rate against quality gate thresholds. Returns verdict (pass/warn/fail) with per-function kill rates and survived mutant details.",args:{patches:exports_external.array(exports_external.object({id:exports_external.string().describe("Unique identifier for the mutation patch"),filePath:exports_external.string().describe("File path to apply the patch to"),functionName:exports_external.string().describe("Function being mutated"),mutationType:exports_external.string().describe("Type of mutation (e.g., off_by_one, null_substitution)"),patch:exports_external.string().describe("Unified diff patch content"),lineNumber:exports_external.number().optional().describe("Line number of the mutation")})).describe("Array of MutationPatch objects — pre-generated mutation patches to execute"),files:exports_external.array(exports_external.string()).describe("Array of test file paths to run against mutants"),test_command:exports_external.array(exports_external.string()).describe('Test command as array of strings (e.g., ["npx", "vitest", "--run"])'),pass_threshold:exports_external.number().optional().describe("Kill rate threshold for pass verdict (default: 0.80)"),warn_threshold:exports_external.number().optional().describe("Kill rate threshold for warn verdict (default: 0.60)"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({error:"files must be a non-empty array of file paths",success:!1},null,2);if(!typedArgs.test_command||!Array.isArray(typedArgs.test_command)||typedArgs.test_command.length===0)return JSON.stringify({error:"test_command must be a non-empty array of strings",success:!1},null,2);if(!typedArgs.test_command.every((c)=>typeof c==="string"))return JSON.stringify({error:"test_command must contain only strings",success:!1},null,2);let cmdValidationError=validateTestCommand(typedArgs.test_command);if(cmdValidationError)return JSON.stringify({error:cmdValidationError,success:!1},null,2);if(!typedArgs.patches||!Array.isArray(typedArgs.patches)||typedArgs.patches.length===0)return JSON.stringify({error:"patches must be a non-empty array of MutationPatch objects",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({success:!1,error:resolved.message},null,2);let cwd=resolved.directory,passThreshold=typedArgs.pass_threshold??0.8,warnThreshold=typedArgs.warn_threshold??0.6,sourceFiles=new Map,uniquePaths=[...new Set(typedArgs.patches.map((p)=>p.filePath))];for(let filePath of uniquePaths)try{let resolvedPath=path276.resolve(cwd,filePath);sourceFiles.set(filePath,fs163.readFileSync(resolvedPath,"utf-8"))}catch{}let report=await executeMutationSuite(typedArgs.patches,typedArgs.test_command,typedArgs.files,cwd,void 0,void 0,sourceFiles.size>0?sourceFiles:void 0),result=evaluateMutationGate(report,passThreshold,warnThreshold);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`mutation_test failed: ${e.message}`:"mutation_test failed: unknown error",success:!1},null,2)}}});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs164 from"node:fs";import*as path277 from"node:path";var OSV_TIMEOUT_MS=60000,OSV_MAX_STDOUT_BYTES=12582912,OSV_MAX_STDERR_BYTES=262144,DEFAULT_MAX_RESULTS3=200,HARD_CAP_RESULTS3=2000;function resolveOsvScannerBinary(){return _internals221.resolveExecutableFromPath(["osv-scanner"])}function normalizeScanPath(value,workspace){let raw=typeof value==="string"&&value.trim()?value.trim():".";if(containsControlChars(raw)||containsPathTraversal(raw))return null;if(path277.isAbsolute(raw)||/^[A-Za-z]:[/\\]/.test(raw))return null;try{let realWorkspace=fs164.realpathSync(workspace),resolved=path277.resolve(realWorkspace,raw),realTarget=fs164.realpathSync(resolved),relative68=path277.relative(realWorkspace,realTarget);if(relative68.startsWith("..")||path277.isAbsolute(relative68))return null;return relative68?relative68.split(path277.sep).join("/"):"."}catch{return null}}function firstString(value){return typeof value==="string"&&value?value:void 0}function collectReferences(vuln){let urls=(Array.isArray(vuln.references)?vuln.references:[]).map((ref)=>ref&&typeof ref==="object"?firstString(ref.url):void 0).filter((url3)=>Boolean(url3));return urls.length>0?urls.slice(0,10):void 0}function parseOsvOutput(stdout,maxResults){let parsed;try{parsed=JSON.parse(stdout)}catch{return{findings:[],total:0,parseError:!0}}let findings=[],total=0,results=Array.isArray(parsed?.results)?parsed.results:[];for(let result of results){let resultObj=result,packages=Array.isArray(resultObj.packages)?resultObj.packages:[];for(let pkg of packages){let pkgObj=pkg,pkgInfo=pkgObj.package??{},vulnerabilities=Array.isArray(pkgObj.vulnerabilities)?pkgObj.vulnerabilities:[];for(let vulnerability of vulnerabilities){let vuln=vulnerability;if(total++,findings.length>=maxResults)continue;let fixedVersion=(Array.isArray(vuln.groups)?vuln.groups:[]).flatMap((group)=>Array.isArray(group.fixed)?group.fixed:[]).map(firstString).find(Boolean);findings.push({id:firstString(vuln.id)??firstString(vuln.osv)??"UNKNOWN",summary:firstString(vuln.summary),packageName:firstString(pkgInfo.name)??firstString(pkgObj.name)??firstString(pkgObj.package),ecosystem:firstString(pkgInfo.ecosystem),installedVersion:firstString(pkgInfo.version)??firstString(pkgObj.version),fixedVersion,aliases:Array.isArray(vuln.aliases)?vuln.aliases.filter((a)=>typeof a==="string"):void 0,references:collectReferences(vuln)})}}}return{findings,total,parseError:!1}}function sanitizeMaxResults2(value){let numeric=typeof value==="number"&&Number.isFinite(value)?value:DEFAULT_MAX_RESULTS3;return Math.min(Math.max(0,numeric),HARD_CAP_RESULTS3)}var osv_scan=createSwarmTool({description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Read-only; resolves osv-scanner lazily.",args:{scan_path:exports_external.string().default(".").describe('Workspace-relative path to scan, default "."'),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS3).describe("Maximum vulnerabilities to return")},execute:async(args2,directory)=>{let obj=typeof args2==="object"&&args2!==null?args2:{},scanPath=normalizeScanPath(obj.scan_path,directory);if(!scanPath)return JSON.stringify({error:!0,type:"path-escape",message:"scan_path must be an existing workspace-relative path"},null,2);let maxResults=sanitizeMaxResults2(obj.max_results),executable=_internals221.resolveOsvScannerBinary();if(!executable)return JSON.stringify({error:!0,type:"osv-scanner-not-found",message:"osv-scanner executable not found. Install OSV-Scanner and ensure osv-scanner is on PATH."},null,2);let osvArgs=["scan","--format","json",scanPath==="."?".":`./${scanPath}`],run=await _internals221.runExternalTool({executable,args:osvArgs,cwd:directory,timeoutMs:OSV_TIMEOUT_MS,maxStdoutBytes:OSV_MAX_STDOUT_BYTES,maxStderrBytes:OSV_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`osv-scanner timed out after ${OSV_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"osv-scanner failed to start"},null,2);let{findings,total,parseError}=parseOsvOutput(run.stdout,maxResults);if(parseError)return JSON.stringify({error:!0,type:"unknown",message:run.stdoutTruncated||run.stderrTruncated?"osv-scanner JSON output was truncated and could not be parsed":"osv-scanner output was not valid JSON"},null,2);if(run.exitCode!==0&&findings.length===0&&run.stderr)return JSON.stringify({error:!0,type:"unknown",message:run.stderr.split(`
|
|
6737
|
-
`)[0]},null,2);return JSON.stringify({clean:total===0&&!run.stdoutTruncated&&!run.stderrTruncated,findings,total,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,command:["osv-scanner",...osvArgs],scanPath,outputTruncated:run.stdoutTruncated||run.stderrTruncated,note:run.exitCode!==0&&total>0?`osv-scanner exited ${run.exitCode} after finding vulnerabilities`:run.stdoutTruncated||run.stderrTruncated?"osv-scanner output was truncated; result is incomplete.":void 0},null,2)}}),_internals221={resolveExecutableFromPath,resolveOsvScannerBinary,runExternalTool,parseOsvOutput};init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_utils2();init_create_tool();import{existsSync as existsSync147}from"node:fs";import*as path278 from"node:path";var ParseLaneCandidatesArgsShape={output_ref:exports_external.string().min(1).describe("Opaque lane output ref returned as output_ref by dispatch_lanes or collect_lane_results."),accept_partial:exports_external.boolean().default(!1).describe("Accept sources where transcriptIncomplete is true (partial transcripts)."),accept_degraded:exports_external.boolean().default(!1).describe("Accept sources where the artifact storage was degraded (output_degraded)."),degraded:exports_external.boolean().default(!1).describe("Passed through from DispatchLaneResult.output_degraded by the orchestrator."),row_format_version:exports_external.number().int().nonnegative().default(1).describe("Row format version; currently only version 1 is supported."),producer:exports_external.string().optional().default("swarm-pr-review").describe("Producer label for cross-skill filtering in the sidecar."),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional().describe("Assert the row family for this dispatch batch. A recognizable conflicting header is refused."),expected_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the base-explorer lane linked to this dispatch provenance. Requires expected_family=base_explorer; mismatched base CLEAN attestations are refused."),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned base-explorer lane set for a consolidated batch. Requires expected_family=base_explorer and expected_lane; owned-but-not-expected lanes are skipped as out-of-scope for this per-lane call instead of refused, while foreign lanes are still refused."),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the micro-lane label linked to this dispatch provenance. Requires expected_family=micro_lane; mismatched candidates and CLEAN attestations are refused."),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned family set of a consolidated depth-tier lane. Requires expected_family=micro_lane and expected_micro_lane; rows for owned-but-not-expected families are skipped as out-of-scope for this per-family call instead of refused, while families outside the set are still refused."),use_lockfile:exports_external.boolean().default(!1).describe("When true, use proper-lockfile for concurrency-safe sidecar writes."),project_root:exports_external.string().optional().describe("Project root directory where .swarm/ lives. Defaults to the injected working directory.")},ParseLaneCandidatesArgsSchema=exports_external.object(ParseLaneCandidatesArgsShape).strict().superRefine((value,context)=>{for(let issue3 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue3.field],message:issue3.message})}),REF_RE2=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/;function laneOutputRelativePath2(ref){let parts=ref.split(":");if(parts.length!==4)return"";let[,batchDigest,laneDigest,outputDigest]=parts;return path278.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}var parse_lane_candidates=createSwarmTool({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.",args:{output_ref:ParseLaneCandidatesArgsShape.output_ref,accept_partial:ParseLaneCandidatesArgsShape.accept_partial,accept_degraded:ParseLaneCandidatesArgsShape.accept_degraded,degraded:ParseLaneCandidatesArgsShape.degraded,row_format_version:ParseLaneCandidatesArgsShape.row_format_version,producer:ParseLaneCandidatesArgsShape.producer,expected_family:ParseLaneCandidatesArgsShape.expected_family,expected_lane:ParseLaneCandidatesArgsShape.expected_lane,expected_lanes:ParseLaneCandidatesArgsShape.expected_lanes,expected_micro_lane:ParseLaneCandidatesArgsShape.expected_micro_lane,expected_micro_lanes:ParseLaneCandidatesArgsShape.expected_micro_lanes,use_lockfile:ParseLaneCandidatesArgsShape.use_lockfile,project_root:ParseLaneCandidatesArgsShape.project_root},async execute(args2,directory){let parsed=ParseLaneCandidatesArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,failure_class:"invalid_args",message:"Invalid parse_lane_candidates arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)},null,2);let{output_ref,accept_partial,accept_degraded,degraded,row_format_version,producer,expected_family,expected_lane,expected_lanes,expected_micro_lane,expected_micro_lanes,use_lockfile,project_root}=parsed.data;if(project_root!==void 0){let absRoot=path278.resolve(project_root),absDir=path278.resolve(directory),rel=path278.relative(absDir,absRoot);if(rel===".."||rel.startsWith(`..${path278.sep}`)||path278.isAbsolute(rel))return JSON.stringify({success:!1,failure_class:"invalid_args",message:"project_root must resolve within the injected working directory",errors:[`project_root: ${project_root} is outside the project root ${directory}`]},null,2)}let loaded;try{loaded=readLaneOutput(directory,output_ref)}catch{loaded=null}if(!loaded){let relPath=REF_RE2.test(output_ref)?laneOutputRelativePath2(output_ref):"",absPath=relPath?validateSwarmPath(directory,relPath):"",artifactStatus=(absPath?existsSync147(absPath):!1)?"artifact-corrupted":"ref-not-found",refParts=output_ref.split(":"),hasValidRef=REF_RE2.test(output_ref)&&refParts.length===4,syntheticBatchId=hasValidRef?refParts[1]:"unknown",syntheticLaneId=hasValidRef?refParts[2]:"unknown",syntheticDigest="0".repeat(64),artifactInput2={output_ref,batchId:syntheticBatchId,laneId:syntheticLaneId,agent:"unknown",role:"unknown",digest:syntheticDigest,text:"",artifact_status:artifactStatus,source:"dispatch_lanes",produced_at:new Date().toISOString()},flags2={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result2=parseAndPersist(artifactInput2,flags2,{projectRoot:project_root??directory,useLockfile:use_lockfile,batchDigest:syntheticBatchId});return JSON.stringify(result2,null,2)}let artifact=loaded.artifact,artifactInput={output_ref:artifact.ref,batchId:artifact.batchId,laneId:artifact.laneId,agent:artifact.agent,role:artifact.role,...artifact.sessionId!==void 0?{sessionId:artifact.sessionId}:{},...artifact.parentSessionId!==void 0?{parentSessionId:artifact.parentSessionId}:{},digest:artifact.digest,text:artifact.text,transcriptIncomplete:artifact.transcriptIncomplete,artifact_status:"ok",source:artifact.source,produced_at:artifact.createdAt??artifact.updatedAt},flags={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result=parseAndPersist(artifactInput,flags,{projectRoot:project_root??directory,useLockfile:use_lockfile});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_manager2();import{createHash as createHash62}from"node:crypto";import*as fs175 from"node:fs";import*as path289 from"node:path";init_utils2();init_logger();init_state3();import*as fs165 from"node:fs";import*as path279 from"node:path";var APPROVAL_TTL_MS=86400000;function readEvidenceDir(directory,phase){try{let dirPath=validateSwarmPath(directory,path279.posix.join("evidence",String(phase)));if(!fs165.existsSync(dirPath))return[];return fs165.readdirSync(dirPath).filter((e)=>e.startsWith("full-auto-")&&e.endsWith(".json")).map((e)=>path279.join(dirPath,e))}catch{return[]}}function parseEvidence(filePath){try{let raw=fs165.readFileSync(filePath,"utf-8");return JSON.parse(raw)}catch(error93){warn(`[full-auto/phase-approval] failed to parse ${filePath}: ${error93 instanceof Error?error93.message:String(error93)}`);return}}function verifyFullAutoPhaseApproval(directory,sessionID,phase,config3){let fullAutoConfig=config3.full_auto;if(!sessionID)return{ok:!0,reason:"no sessionID — gate skipped"};if(!isFullAutoRunActive(directory,sessionID))return{ok:!0,reason:"no active Full-Auto run"};let failClosed=fullAutoConfig?.fail_closed!==!1,files=readEvidenceDir(directory,phase);if(files.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no full-auto oversight evidence found at .swarm/evidence/${phase}/`}:{ok:!0,reason:"no evidence and fail_closed=false"};let phaseBoundary=files.map((f)=>parseEvidence(f)).filter((e)=>Boolean(e)).filter((e)=>e.phase===phase&&e.trigger_source==="phase_boundary"&&(e.verdict??"").toUpperCase()==="APPROVED");if(phaseBoundary.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no phase-boundary oversight record found for phase ${phase}`}:{ok:!0,reason:"no phase-boundary record and fail_closed=false"};phaseBoundary.sort((a,b)=>{let ta=a.timestamp?Date.parse(a.timestamp):0;return(b.timestamp?Date.parse(b.timestamp):0)-ta});let latest=phaseBoundary[0],verdict=latest.verdict?.toUpperCase()??"";if(verdict!=="APPROVED")return{ok:!1,reason:`Full-Auto oversight verdict for phase ${phase} is ${verdict||"MISSING"} (required: APPROVED)`,evidence:latest};let FORWARD_SKEW_MS=300000,ts=latest.timestamp?Date.parse(latest.timestamp):0,age=Date.now()-ts;if(!ts||age<-FORWARD_SKEW_MS||age>APPROVAL_TTL_MS)return{ok:!1,reason:age<-FORWARD_SKEW_MS?`Full-Auto oversight evidence for phase ${phase} has a future timestamp (${latest.timestamp}); rejected as forged or clock-skewed`:`Full-Auto oversight evidence for phase ${phase} is stale (>24h)`,evidence:latest};if((Array.isArray(latest.evidence_checked)?latest.evidence_checked:[]).length===0){let exception=phaseIsExplicitlyNonCode(directory,phase),runState=loadFullAutoRunState(directory,sessionID),codeWorkObserved=(runState?.counters.coderDelegations??0)>0||(runState?.counters.toolCalls??0)>0;if(!exception||codeWorkObserved)return{ok:!1,reason:!exception?`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked and the phase is not declared non-code in plan.json (required: at least one verification source)`:`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked while run counters indicate code work was performed`,evidence:latest};return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp} (non-code phase exception)`,evidence:latest}}return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp}`,evidence:latest}}function phaseIsExplicitlyNonCode(directory,phase){try{let planPath=validateSwarmPath(directory,"plan.json");if(!fs165.existsSync(planPath))return!1;let raw=fs165.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw),entry=(Array.isArray(plan.phases)?plan.phases:[]).find((p)=>p.id===phase||p.phase===phase);if(!entry)return!1;if(entry.non_code===!0)return!0;let kindOrType=(entry.kind??entry.type??"").toString().toLowerCase();return["docs","documentation","spec","specification","research","planning","plan","non_code","non-code","noncode"].includes(kindOrType)}catch(error93){return warn(`[full-auto/phase-approval] plan.json inspection failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}init_gate_evidence();init_curator();init_curator_llm_factory();init_extractors();init_knowledge_curator();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_events();init_knowledge_receipt_ledger();function classifyDirectiveGateFailure(error93){if(typeof error93==="object"&&error93!==null&&"ok"in error93&&error93.ok===!1&&"code"in error93){let unavailable2=error93;if(unavailable2.code==="store_corrupt")return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(unavailable2.code==="lock_timeout")return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};error93=unavailable2.detail}let lower=(error93 instanceof Error?error93.message:typeof error93==="string"?error93:"").toLowerCase();if(lower.includes("exact session identity"))return{failure:{code:"RECEIPT_MISSING",action_id:"knowledge_receipt"},recovery:{kind:"tool",action:"knowledge_receipt"}};if(lower.includes("corrupt")||lower.includes("legacy_unverifiable"))return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("lock_timeout"))return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};if(lower.includes("project root")||lower.includes("root"))return{failure:{code:"RECEIPT_WRONG_ROOT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("eacces")||lower.includes("eperm")||lower.includes("permission"))return{failure:{code:"RECEIPT_PERMISSION",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("ebusy")||lower.includes("temporar")||lower.includes("transient"))return{failure:{code:"RECEIPT_TRANSIENT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};return{failure:{code:"RECEIPT_STORE_UNAVAILABLE",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}}}async function evaluatePhaseCriticalDirectives(params){try{if(!params.phaseLabel?.trim())throw Error("directive gate requires exact phase identity");let state=await queryLiveMemberships(params.directory,{phase:params.phaseLabel,session_id:params.sessionId?.trim()||void 0,include_terminal:!0,include_phase_closed:!1});if(!state.ok)return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(state)};let criticals=state.memberships.filter((membership)=>membership.critical);if(!params.sessionId?.trim()&&criticals.length>0)throw Error("directive gate requires exact session identity");if(criticals.length===0)return{blocked:!1,unresolved:[],overridden:[],failedClosed:!1};let unresolved=[],overridden=[];for(let membership of criticals){let terminal=membership.terminal;if(terminal?.authorized_transition){overridden.push(membership.entry_id);continue}if(terminal?.outcome==="applied")continue;if((terminal?.outcome==="ignored"||terminal?.outcome==="n_a")&&terminal.reason?.trim())continue;unresolved.push({id:membership.entry_id,trace_id:membership.trace_id,reason:terminal?.outcome==="violated"||terminal?.outcome==="contradicted"?"unremediated_violation":"no_verdict"})}return{blocked:unresolved.length>0,unresolved,overridden,failedClosed:!1}}catch(error93){return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(error93)}}}async function recordDirectiveOverrides(directory,ids,justification,sessionId,phaseLabel){if(!justification.trim())throw Error("directive override requires a written justification");if(!sessionId?.trim()||!phaseLabel?.trim())throw Error("directive override requires exact session and phase identity");let state=await queryLiveMemberships(directory,{phase:phaseLabel,session_id:sessionId,include_terminal:!0,include_phase_closed:!1});if(!state.ok)throw Error(state.detail);let criticals=state.memberships.filter((membership)=>membership.critical),selected=ids.map((requested)=>{let exact=criticals.filter((membership)=>`${membership.trace_id}/${membership.entry_id}`===requested);if(exact.length===1)return exact[0];let byEntry=criticals.filter((membership)=>membership.entry_id===requested);if(byEntry.length!==1)throw Error(byEntry.length===0?`unknown directive override target: ${requested}`:`ambiguous directive override target; use trace_id/entry_id: ${requested}`);return byEntry[0]});for(let membership of selected){let outcome=membership.terminal?.outcome??"n_a",committed=await validateAndCommitTerminalBatch(directory,{trace_id:membership.trace_id,session_id:sessionId,phase:phaseLabel,task_id:membership.task_id,items:[{entry_id:membership.entry_id,outcome,source:"phase_override",reason:justification}],authorization:{actor:"phase-override",reason:justification,expected_event_id:membership.terminal?.event_id??""}});if(!committed.ok||committed.rejected.length>0)throw Error("failed to persist authoritative directive override");try{await recordKnowledgeEvent(directory,{type:"override",trace_id:membership.trace_id,knowledge_id:membership.entry_id,session_id:sessionId,agent:"architect",source:"phase_override",reason:`override: ${justification}`.slice(0,280)})}catch{}}}function formatDirectiveBlockMessage(unresolved){return["PHASE_COMPLETE_BLOCKED: unresolved critical knowledge directive(s):",...unresolved.map((u)=>{let why=u.reason==="no_verdict"?"no terminal verdict (applied/verified/ignored+reason/n_a+reason)":"violated with no subsequent applied/verified remediation";return` - ${u.trace_id?`${u.trace_id}/${u.id}`:u.id}: ${why}`}),"Resolve each by applying/verifying the directive, recording an explicit","ignored/n_a with a reason, or use the separate architect-only record_directive_override action with a","written justification."].join(`
|
|
6738
|
+
`)[0]},null,2);return JSON.stringify({clean:total===0&&!run.stdoutTruncated&&!run.stderrTruncated,findings,total,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,command:["osv-scanner",...osvArgs],scanPath,outputTruncated:run.stdoutTruncated||run.stderrTruncated,note:run.exitCode!==0&&total>0?`osv-scanner exited ${run.exitCode} after finding vulnerabilities`:run.stdoutTruncated||run.stderrTruncated?"osv-scanner output was truncated; result is incomplete.":void 0},null,2)}}),_internals221={resolveExecutableFromPath,resolveOsvScannerBinary,runExternalTool,parseOsvOutput};init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_utils2();init_create_tool();import{existsSync as existsSync148}from"node:fs";import*as path278 from"node:path";var ParseLaneCandidatesArgsShape={output_ref:exports_external.string().min(1).describe("Opaque lane output ref returned as output_ref by dispatch_lanes or collect_lane_results."),accept_partial:exports_external.boolean().default(!1).describe("Accept sources where transcriptIncomplete is true (partial transcripts)."),accept_degraded:exports_external.boolean().default(!1).describe("Accept sources where the artifact storage was degraded (output_degraded)."),degraded:exports_external.boolean().default(!1).describe("Passed through from DispatchLaneResult.output_degraded by the orchestrator."),row_format_version:exports_external.number().int().nonnegative().default(1).describe("Row format version; currently only version 1 is supported."),producer:exports_external.string().optional().default("swarm-pr-review").describe("Producer label for cross-skill filtering in the sidecar."),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional().describe("Assert the row family for this dispatch batch. A recognizable conflicting header is refused."),expected_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the base-explorer lane linked to this dispatch provenance. Requires expected_family=base_explorer; mismatched base CLEAN attestations are refused."),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned base-explorer lane set for a consolidated batch. Requires expected_family=base_explorer and expected_lane; owned-but-not-expected lanes are skipped as out-of-scope for this per-lane call instead of refused, while foreign lanes are still refused."),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional().describe("Assert the micro-lane label linked to this dispatch provenance. Requires expected_family=micro_lane; mismatched candidates and CLEAN attestations are refused."),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Full owned family set of a consolidated depth-tier lane. Requires expected_family=micro_lane and expected_micro_lane; rows for owned-but-not-expected families are skipped as out-of-scope for this per-family call instead of refused, while families outside the set are still refused."),use_lockfile:exports_external.boolean().default(!1).describe("When true, use proper-lockfile for concurrency-safe sidecar writes."),project_root:exports_external.string().optional().describe("Project root directory where .swarm/ lives. Defaults to the injected working directory.")},ParseLaneCandidatesArgsSchema=exports_external.object(ParseLaneCandidatesArgsShape).strict().superRefine((value,context)=>{for(let issue3 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue3.field],message:issue3.message})}),REF_RE2=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/;function laneOutputRelativePath2(ref){let parts=ref.split(":");if(parts.length!==4)return"";let[,batchDigest,laneDigest,outputDigest]=parts;return path278.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}var parse_lane_candidates=createSwarmTool({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.",args:{output_ref:ParseLaneCandidatesArgsShape.output_ref,accept_partial:ParseLaneCandidatesArgsShape.accept_partial,accept_degraded:ParseLaneCandidatesArgsShape.accept_degraded,degraded:ParseLaneCandidatesArgsShape.degraded,row_format_version:ParseLaneCandidatesArgsShape.row_format_version,producer:ParseLaneCandidatesArgsShape.producer,expected_family:ParseLaneCandidatesArgsShape.expected_family,expected_lane:ParseLaneCandidatesArgsShape.expected_lane,expected_lanes:ParseLaneCandidatesArgsShape.expected_lanes,expected_micro_lane:ParseLaneCandidatesArgsShape.expected_micro_lane,expected_micro_lanes:ParseLaneCandidatesArgsShape.expected_micro_lanes,use_lockfile:ParseLaneCandidatesArgsShape.use_lockfile,project_root:ParseLaneCandidatesArgsShape.project_root},async execute(args2,directory){let parsed=ParseLaneCandidatesArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,failure_class:"invalid_args",message:"Invalid parse_lane_candidates arguments",errors:parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`)},null,2);let{output_ref,accept_partial,accept_degraded,degraded,row_format_version,producer,expected_family,expected_lane,expected_lanes,expected_micro_lane,expected_micro_lanes,use_lockfile,project_root}=parsed.data;if(project_root!==void 0){let absRoot=path278.resolve(project_root),absDir=path278.resolve(directory),rel=path278.relative(absDir,absRoot);if(rel===".."||rel.startsWith(`..${path278.sep}`)||path278.isAbsolute(rel))return JSON.stringify({success:!1,failure_class:"invalid_args",message:"project_root must resolve within the injected working directory",errors:[`project_root: ${project_root} is outside the project root ${directory}`]},null,2)}let loaded;try{loaded=readLaneOutput(directory,output_ref)}catch{loaded=null}if(!loaded){let relPath=REF_RE2.test(output_ref)?laneOutputRelativePath2(output_ref):"",absPath=relPath?validateSwarmPath(directory,relPath):"",artifactStatus=(absPath?existsSync148(absPath):!1)?"artifact-corrupted":"ref-not-found",refParts=output_ref.split(":"),hasValidRef=REF_RE2.test(output_ref)&&refParts.length===4,syntheticBatchId=hasValidRef?refParts[1]:"unknown",syntheticLaneId=hasValidRef?refParts[2]:"unknown",syntheticDigest="0".repeat(64),artifactInput2={output_ref,batchId:syntheticBatchId,laneId:syntheticLaneId,agent:"unknown",role:"unknown",digest:syntheticDigest,text:"",artifact_status:artifactStatus,source:"dispatch_lanes",produced_at:new Date().toISOString()},flags2={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result2=parseAndPersist(artifactInput2,flags2,{projectRoot:project_root??directory,useLockfile:use_lockfile,batchDigest:syntheticBatchId});return JSON.stringify(result2,null,2)}let artifact=loaded.artifact,artifactInput={output_ref:artifact.ref,batchId:artifact.batchId,laneId:artifact.laneId,agent:artifact.agent,role:artifact.role,...artifact.sessionId!==void 0?{sessionId:artifact.sessionId}:{},...artifact.parentSessionId!==void 0?{parentSessionId:artifact.parentSessionId}:{},digest:artifact.digest,text:artifact.text,transcriptIncomplete:artifact.transcriptIncomplete,artifact_status:"ok",source:artifact.source,produced_at:artifact.createdAt??artifact.updatedAt},flags={accept_partial,accept_degraded,degraded,row_format_version,...producer?{producer}:{},...expected_family?{expected_family}:{},...expected_lane?{expected_lane}:{},...expected_lanes?{expected_lanes}:{},...expected_micro_lane?{expected_micro_lane}:{},...expected_micro_lanes?{expected_micro_lanes}:{}},result=parseAndPersist(artifactInput,flags,{projectRoot:project_root??directory,useLockfile:use_lockfile});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_manager2();import{createHash as createHash62}from"node:crypto";import*as fs175 from"node:fs";import*as path289 from"node:path";init_utils2();init_logger();init_state3();import*as fs165 from"node:fs";import*as path279 from"node:path";var APPROVAL_TTL_MS=86400000;function readEvidenceDir(directory,phase){try{let dirPath=validateSwarmPath(directory,path279.posix.join("evidence",String(phase)));if(!fs165.existsSync(dirPath))return[];return fs165.readdirSync(dirPath).filter((e)=>e.startsWith("full-auto-")&&e.endsWith(".json")).map((e)=>path279.join(dirPath,e))}catch{return[]}}function parseEvidence(filePath){try{let raw=fs165.readFileSync(filePath,"utf-8");return JSON.parse(raw)}catch(error93){warn(`[full-auto/phase-approval] failed to parse ${filePath}: ${error93 instanceof Error?error93.message:String(error93)}`);return}}function verifyFullAutoPhaseApproval(directory,sessionID,phase,config3){let fullAutoConfig=config3.full_auto;if(!sessionID)return{ok:!0,reason:"no sessionID — gate skipped"};if(!isFullAutoRunActive(directory,sessionID))return{ok:!0,reason:"no active Full-Auto run"};let failClosed=fullAutoConfig?.fail_closed!==!1,files=readEvidenceDir(directory,phase);if(files.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no full-auto oversight evidence found at .swarm/evidence/${phase}/`}:{ok:!0,reason:"no evidence and fail_closed=false"};let phaseBoundary=files.map((f)=>parseEvidence(f)).filter((e)=>Boolean(e)).filter((e)=>e.phase===phase&&e.trigger_source==="phase_boundary"&&(e.verdict??"").toUpperCase()==="APPROVED");if(phaseBoundary.length===0)return failClosed?{ok:!1,reason:`Full-Auto v2 active but no phase-boundary oversight record found for phase ${phase}`}:{ok:!0,reason:"no phase-boundary record and fail_closed=false"};phaseBoundary.sort((a,b)=>{let ta=a.timestamp?Date.parse(a.timestamp):0;return(b.timestamp?Date.parse(b.timestamp):0)-ta});let latest=phaseBoundary[0],verdict=latest.verdict?.toUpperCase()??"";if(verdict!=="APPROVED")return{ok:!1,reason:`Full-Auto oversight verdict for phase ${phase} is ${verdict||"MISSING"} (required: APPROVED)`,evidence:latest};let FORWARD_SKEW_MS=300000,ts=latest.timestamp?Date.parse(latest.timestamp):0,age=Date.now()-ts;if(!ts||age<-FORWARD_SKEW_MS||age>APPROVAL_TTL_MS)return{ok:!1,reason:age<-FORWARD_SKEW_MS?`Full-Auto oversight evidence for phase ${phase} has a future timestamp (${latest.timestamp}); rejected as forged or clock-skewed`:`Full-Auto oversight evidence for phase ${phase} is stale (>24h)`,evidence:latest};if((Array.isArray(latest.evidence_checked)?latest.evidence_checked:[]).length===0){let exception=phaseIsExplicitlyNonCode(directory,phase),runState=loadFullAutoRunState(directory,sessionID),codeWorkObserved=(runState?.counters.coderDelegations??0)>0||(runState?.counters.toolCalls??0)>0;if(!exception||codeWorkObserved)return{ok:!1,reason:!exception?`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked and the phase is not declared non-code in plan.json (required: at least one verification source)`:`Full-Auto oversight evidence for phase ${phase} has empty evidence_checked while run counters indicate code work was performed`,evidence:latest};return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp} (non-code phase exception)`,evidence:latest}}return{ok:!0,reason:`Full-Auto oversight APPROVED at ${latest.timestamp}`,evidence:latest}}function phaseIsExplicitlyNonCode(directory,phase){try{let planPath=validateSwarmPath(directory,"plan.json");if(!fs165.existsSync(planPath))return!1;let raw=fs165.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw),entry=(Array.isArray(plan.phases)?plan.phases:[]).find((p)=>p.id===phase||p.phase===phase);if(!entry)return!1;if(entry.non_code===!0)return!0;let kindOrType=(entry.kind??entry.type??"").toString().toLowerCase();return["docs","documentation","spec","specification","research","planning","plan","non_code","non-code","noncode"].includes(kindOrType)}catch(error93){return warn(`[full-auto/phase-approval] plan.json inspection failed: ${error93 instanceof Error?error93.message:String(error93)}`),!1}}init_gate_evidence();init_curator();init_curator_llm_factory();init_extractors();init_knowledge_curator();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_events();init_knowledge_receipt_ledger();function classifyDirectiveGateFailure(error93){if(typeof error93==="object"&&error93!==null&&"ok"in error93&&error93.ok===!1&&"code"in error93){let unavailable2=error93;if(unavailable2.code==="store_corrupt")return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(unavailable2.code==="lock_timeout")return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};error93=unavailable2.detail}let lower=(error93 instanceof Error?error93.message:typeof error93==="string"?error93:"").toLowerCase();if(lower.includes("exact session identity"))return{failure:{code:"RECEIPT_MISSING",action_id:"knowledge_receipt"},recovery:{kind:"tool",action:"knowledge_receipt"}};if(lower.includes("corrupt")||lower.includes("legacy_unverifiable"))return{failure:{code:"RECEIPT_CORRUPT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("lock_timeout"))return{failure:{code:"RECEIPT_LOCK_TIMEOUT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};if(lower.includes("project root")||lower.includes("root"))return{failure:{code:"RECEIPT_WRONG_ROOT",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("eacces")||lower.includes("eperm")||lower.includes("permission"))return{failure:{code:"RECEIPT_PERMISSION",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}};if(lower.includes("ebusy")||lower.includes("temporar")||lower.includes("transient"))return{failure:{code:"RECEIPT_TRANSIENT",action_id:"phase_complete"},recovery:{kind:"retry",action:"phase_complete"}};return{failure:{code:"RECEIPT_STORE_UNAVAILABLE",action_id:"repair_knowledge_receipt_ledger"},recovery:{kind:"tool",action:"repair_knowledge_receipt_ledger"}}}async function evaluatePhaseCriticalDirectives(params){try{if(!params.phaseLabel?.trim())throw Error("directive gate requires exact phase identity");let state=await queryLiveMemberships(params.directory,{phase:params.phaseLabel,session_id:params.sessionId?.trim()||void 0,include_terminal:!0,include_phase_closed:!1});if(!state.ok)return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(state)};let criticals=state.memberships.filter((membership)=>membership.critical);if(!params.sessionId?.trim()&&criticals.length>0)throw Error("directive gate requires exact session identity");if(criticals.length===0)return{blocked:!1,unresolved:[],overridden:[],failedClosed:!1};let unresolved=[],overridden=[];for(let membership of criticals){let terminal=membership.terminal;if(terminal?.authorized_transition){overridden.push(membership.entry_id);continue}if(terminal?.outcome==="applied")continue;if((terminal?.outcome==="ignored"||terminal?.outcome==="n_a")&&terminal.reason?.trim())continue;unresolved.push({id:membership.entry_id,trace_id:membership.trace_id,reason:terminal?.outcome==="violated"||terminal?.outcome==="contradicted"?"unremediated_violation":"no_verdict"})}return{blocked:unresolved.length>0,unresolved,overridden,failedClosed:!1}}catch(error93){return{blocked:!0,unresolved:[],overridden:[],failedClosed:!0,...classifyDirectiveGateFailure(error93)}}}async function recordDirectiveOverrides(directory,ids,justification,sessionId,phaseLabel){if(!justification.trim())throw Error("directive override requires a written justification");if(!sessionId?.trim()||!phaseLabel?.trim())throw Error("directive override requires exact session and phase identity");let state=await queryLiveMemberships(directory,{phase:phaseLabel,session_id:sessionId,include_terminal:!0,include_phase_closed:!1});if(!state.ok)throw Error(state.detail);let criticals=state.memberships.filter((membership)=>membership.critical),selected=ids.map((requested)=>{let exact=criticals.filter((membership)=>`${membership.trace_id}/${membership.entry_id}`===requested);if(exact.length===1)return exact[0];let byEntry=criticals.filter((membership)=>membership.entry_id===requested);if(byEntry.length!==1)throw Error(byEntry.length===0?`unknown directive override target: ${requested}`:`ambiguous directive override target; use trace_id/entry_id: ${requested}`);return byEntry[0]});for(let membership of selected){let outcome=membership.terminal?.outcome??"n_a",committed=await validateAndCommitTerminalBatch(directory,{trace_id:membership.trace_id,session_id:sessionId,phase:phaseLabel,task_id:membership.task_id,items:[{entry_id:membership.entry_id,outcome,source:"phase_override",reason:justification}],authorization:{actor:"phase-override",reason:justification,expected_event_id:membership.terminal?.event_id??""}});if(!committed.ok||committed.rejected.length>0)throw Error("failed to persist authoritative directive override");try{await recordKnowledgeEvent(directory,{type:"override",trace_id:membership.trace_id,knowledge_id:membership.entry_id,session_id:sessionId,agent:"architect",source:"phase_override",reason:`override: ${justification}`.slice(0,280)})}catch{}}}function formatDirectiveBlockMessage(unresolved){return["PHASE_COMPLETE_BLOCKED: unresolved critical knowledge directive(s):",...unresolved.map((u)=>{let why=u.reason==="no_verdict"?"no terminal verdict (applied/verified/ignored+reason/n_a+reason)":"violated with no subsequent applied/verified remediation";return` - ${u.trace_id?`${u.trace_id}/${u.id}`:u.id}: ${why}`}),"Resolve each by applying/verifying the directive, recording an explicit","ignored/n_a with a reason, or use the separate architect-only record_directive_override action with a","written justification."].join(`
|
|
6738
6739
|
`)}init_review_receipt();init_skill_usage_log();init_utils2();init_file_locks();init_plan_schema();init_ledger();init_utils3();init_warning_buffer();init_logger();init_project_boundary();init_manager();import*as fs166 from"node:fs";import*as path280 from"node:path";var _fsInternals={mkdirSync:(...args2)=>fs166.mkdirSync(...args2),writeFileSync:(path281,data,encoding)=>fs166.writeFileSync(path281,data,encoding??"utf8"),readFileSync:(path281,encoding)=>fs166.readFileSync(path281,encoding??"utf8"),existsSync:(path281)=>fs166.existsSync(path281)};async function writeCheckpoint(directory){try{assertProjectRoot(directory);let plan=await loadPlan(directory);if(!plan)return;let exportDir=path280.join(directory,".swarm","plan-export");_fsInternals.mkdirSync(exportDir,{recursive:!0});let jsonPath=path280.join(exportDir,"SWARM_PLAN.json"),mdPath=path280.join(exportDir,"SWARM_PLAN.md");_fsInternals.writeFileSync(jsonPath,JSON.stringify(plan,null,2));let md=derivePlanMarkdown(plan),header=`<!--
|
|
6739
6740
|
AUTO-GENERATED EXPORT/CHECKPOINT SNAPSHOT — DO NOT EDIT
|
|
6740
6741
|
This file is NOT the live plan. It is a derived export artifact.
|
|
@@ -6805,7 +6806,7 @@ ${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=
|
|
|
6805
6806
|
`);for(let i=0;i<lines.length;i++){let line=lines[i];if(regex.test(line)){if(total++,matches.length<opts.maxResults)matches.push({file:file3,lineNumber:i+1,lineText:truncateLine(line,opts.maxLines)});regex.lastIndex=0}}}return{matches,truncated:truncated||total>opts.maxResults,total,query:opts.query,mode:opts.mode,maxResults:opts.maxResults,engine:"fallback",warning:"Fallback search uses bounded filesystem traversal and does not fully emulate ripgrep gitignore behavior."}}var search=createSwarmTool({description:"Search for text within workspace files using ripgrep-style interface. Supports literal and regex search modes with glob include/exclude filtering. Returns structured JSON output with file paths, line numbers, and line content.",args:{query:exports_external.string().describe("Search query string (literal or regex depending on mode)"),mode:exports_external.enum(["literal","regex"]).default("literal").describe("Search mode: literal for exact string match, regex for regular expression"),include:exports_external.string().optional().describe('Glob pattern for files to include (e.g., "*.ts", "src/**/*.js"). An exact repo-relative path under a dot-directory (e.g., ".swarm/bundled-skills/<slug>/SKILL.md") is searched directly, bypassing hidden-directory and ignore filtering; .git content is never searchable.'),exclude:exports_external.string().optional().describe('Glob pattern for files to exclude (e.g., "node_modules/**", "*.test.ts")'),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS4).describe("Maximum number of matches to return"),max_lines:exports_external.number().default(DEFAULT_MAX_LINES).describe("Maximum characters per line in results")},execute:async(args2,directory)=>{let query,mode="literal",include,exclude,maxResults=DEFAULT_MAX_RESULTS4,maxLines=DEFAULT_MAX_LINES;try{let obj=args2;query=String(obj.query??""),mode=obj.mode==="regex"?"regex":"literal",include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS4,sanitizedMaxResults=Number.isNaN(rawMaxResults)?DEFAULT_MAX_RESULTS4:rawMaxResults;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS4);let rawMaxLines=typeof obj.max_lines==="number"?obj.max_lines:DEFAULT_MAX_LINES,sanitizedMaxLines=Number.isNaN(rawMaxLines)?DEFAULT_MAX_LINES:rawMaxLines;maxLines=Math.min(Math.max(0,sanitizedMaxLines),HARD_CAP_LINES)}catch{return JSON.stringify({error:!0,type:"invalid-query",message:"Could not parse search arguments"},null,2)}if(!query||query.trim()==="")return JSON.stringify({error:!0,type:"invalid-query",message:"Query cannot be empty"},null,2);if(query.length>MAX_QUERY_LENGTH)return JSON.stringify({error:!0,type:"invalid-query",message:`Query exceeds maximum length of ${MAX_QUERY_LENGTH} characters`},null,2);if(containsControlChars(query))return JSON.stringify({error:!0,type:"invalid-query",message:"Query contains invalid control characters"},null,2);if(include&&splitGlobPatterns2(include).length>MAX_INCLUDE_PATTERNS)return JSON.stringify({error:!0,type:"invalid-query",message:`Too many include patterns (max ${MAX_INCLUDE_PATTERNS})`},null,2);if(exclude&&splitGlobPatterns2(exclude).length>MAX_INCLUDE_PATTERNS)return JSON.stringify({error:!0,type:"invalid-query",message:`Too many exclude patterns (max ${MAX_INCLUDE_PATTERNS})`},null,2);if(include&&containsPathTraversal(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains path traversal sequence"},null,2);if(exclude&&containsPathTraversal(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains path traversal sequence"},null,2);if(include&&containsWindowsAttacks4(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains invalid Windows-specific sequence"},null,2);if(exclude&&containsWindowsAttacks4(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains invalid Windows-specific sequence"},null,2);if(!fs188.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let result;if(_internals231.resolveRipgrepBinary())result=await ripgrepSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});else result=await fallbackSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});if("error"in result&&result.error)return JSON.stringify(result,null,2);return JSON.stringify(result,null,2)}}),_internals231={resolvePackagedRipgrep,resolveExecutableFromPath,resolveRipgrepBinary,runExternalTool,fallbackSearch};init_secretscan();init_zod();init_qa_gate_profile();init_manager();init_create_tool();var _internals232={setGatesForIdentity};async function executeSetQaGates(args2,directory){let plan=await loadPlanJsonOnly(directory),identity=resolveQaGatePlanIdentity(plan,args2);if(!identity.success)return{success:!1,reason:identity.reason,message:identity.message};let planId=identity.planId,currentPlanMatchesIdentity=plan?.swarm===identity.identity.swarm&&plan?.title===identity.identity.title,partial3={},gateKeys=["reviewer","test_engineer","council_mode","sme_enabled","critic_pre_plan","hallucination_guard","sast_enabled","mutation_test","phase_council","drift_check","final_council"];for(let key of gateKeys)if(args2[key]!==void 0)partial3[key]=args2[key];let bindingOnlyRequested=args2.adopt_legacy_binding_only===!0,hasGatePatch=Object.keys(partial3).length>0;if(bindingOnlyRequested&&(hasGatePatch||args2.project_type!==void 0))return{success:!1,reason:"binding_only_patch_conflict",message:"adopt_legacy_binding_only performs exact-binding recovery only. Omit all gate booleans and project_type when using it."};if(bindingOnlyRequested&&!currentPlanMatchesIdentity)return{success:!1,reason:"adopt_legacy_requires_current_plan",message:"adopt_legacy_binding_only may only target the exact current persisted plan identity. Re-run it from the active plan without replacing swarm_id or plan_title."};if(bindingOnlyRequested){let lookup=getProfileLookupForIdentity(directory,identity.identity);if(lookup.kind==="missing")return{success:!1,reason:"no_profile",plan_id:planId,message:"No legacy QA gate profile row exists for this exact current plan identity, so there is nothing to adopt."};if(lookup.kind==="bound")return{success:!0,plan_id:planId,message:`QA gate profile is already exact-bound for plan_id=${planId}; no gates or lock state changed.`,profile:{plan_id:lookup.profile.plan_id,gates:{...lookup.profile.gates},locked_at:lookup.profile.locked_at,locked_by_snapshot_seq:lookup.profile.locked_by_snapshot_seq,profile_hash:computeProfileHash(lookup.profile)}}}try{let updated=_internals232.setGatesForIdentity(directory,identity.identity,partial3,{projectType:args2.project_type,allowLegacyAdoption:currentPlanMatchesIdentity,allowLegacyCollisionCreate:!currentPlanMatchesIdentity,legacyAdoptionIdentity:plan?{swarm:plan.swarm,title:plan.title}:void 0});return{success:!0,plan_id:planId,message:bindingOnlyRequested?`Legacy QA gate profile exact-bound for plan_id=${planId} without changing gates or lock state.`:`QA gates updated for plan_id=${planId}`,profile:{plan_id:updated.plan_id,gates:{...updated.gates},locked_at:updated.locked_at,locked_by_snapshot_seq:updated.locked_by_snapshot_seq,profile_hash:computeProfileHash(updated)}}}catch(err2){let msg=err2 instanceof Error?err2.message:String(err2),lower=msg.toLowerCase(),reason="set_gates_failed";if(err2 instanceof QaGateProfileIdentityUnboundError)reason="plan_identity_unbound";if(lower.includes("locked"))reason="profile_locked";else if(lower.includes("ratchet"))reason="ratchet_violation";else if(bindingOnlyRequested)reason="binding_only_failed";return{success:!1,reason,message:err2 instanceof QaGateProfileIdentityUnboundError?`${msg} ${formatLegacyQaBindingOnlyCall(identity.identity)} is the only supported adoption path for locked or upgraded legacy rows.`:msg,plan_id:planId}}}var set_qa_gates=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Configure the QA gate profile for the current or exact future plan. Architect-only. The initial selection accepts explicit true and false values; later calls can enable additional gates but cannot disable enabled gates. Rejects writes once locked (after critic approval). Creates the initial profile atomically from defaults plus the explicit selection. Uses plan.json identity by default, or exact swarm_id + plan_title before a plan exists.",args:{swarm_id:exports_external.string().refine((value)=>value.trim().length>0,"Must not be blank").optional().describe("Exact swarm identity for pre-plan QA selection. Must be provided with plan_title."),plan_title:exports_external.string().refine((value)=>value.trim().length>0,"Must not be blank").optional().describe("Exact future plan title for pre-plan QA selection. Must be provided with swarm_id."),confirm_identity_change:exports_external.boolean().optional().describe("Confirm that an explicit swarm_id/plan_title pair intentionally replaces the current plan identity."),reviewer:exports_external.boolean().optional().describe("Select the reviewer gate; later calls cannot turn it off once enabled."),test_engineer:exports_external.boolean().optional().describe("Enable the test_engineer gate (true) — cannot be disabled once on."),council_mode:exports_external.boolean().optional().describe("Enable council mode — replaces per-task Stage B (reviewer + test_engineer) with the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task."),sme_enabled:exports_external.boolean().optional().describe("Enable SME consultation."),critic_pre_plan:exports_external.boolean().optional().describe("Enable critic_pre_plan review before plan approval."),hallucination_guard:exports_external.boolean().optional().describe("Enable hallucination_guard checks on plan and implementation claims."),sast_enabled:exports_external.boolean().optional().describe("Enable SAST scanning as a required QA gate."),mutation_test:exports_external.boolean().optional().describe("Enable the mutation-testing gate (default: off). Requires mutation tests to achieve a passing kill rate before phase completion; WARN verdict allows advancement, FAIL blocks."),phase_council:exports_external.boolean().optional().describe("Enable the phase_council gate (default: off). When on, a full 5-member council (critic, reviewer, sme, test_engineer, explorer) reviews all work completed in a phase holistically at phase_complete time. Requires council.enabled: true in config."),drift_check:exports_external.boolean().optional().describe("Enable drift verification gate (default: on). Blocks phase_complete until drift-verifier.json has an approved verdict. When disabled, drift verification is skipped entirely."),final_council:exports_external.boolean().optional().describe("Enable the final_council gate (default: off). When on, after all phases complete the architect dispatches critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collects their CouncilMemberVerdict objects, and calls write_final_council_evidence. This is not General Council mode and does not require council.general.enabled."),project_type:exports_external.string().optional().describe('Project type label (e.g. "ts", "python"). Only applied when the profile is being created for the first time.'),adopt_legacy_binding_only:exports_external.boolean().optional().describe("Operational recovery for upgraded legacy rows. When true, exact-binds the existing current-plan QA profile without changing any gates or its lock. Omit all gate booleans and project_type when using this action.")},execute:async(args2,directory)=>{return JSON.stringify(await executeSetQaGates(args2??{},directory),null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_apply=createSwarmTool({description:"Activate a draft skill proposal (.swarm/skills/proposals/<slug>.md) into .opencode/skills/generated/<slug>/SKILL.md.",args:{slug:exports_external.string().min(1).describe("Slug of the proposal to activate."),force:exports_external.boolean().optional().default(!1).describe("Overwrite an existing active SKILL.md even if it lacks the generator stamp. Default false."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate the proposal against .swarm/skills/evals/<slug> before activation. Default false."),confirm_unevaluated:exports_external.boolean().optional().default(!1).describe('Allow activation when evaluateSkillChange returns status "unevaluated" (no eval set exists). Default false — the activation is blocked with a surfaced reason so the caller can confirm. Generated skills auto-derive an eval stub from their source directives, so this only applies to non-directive skills with no stub.')},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({activated:!1,reason:"slug required"});let result=await activateProposal(directory,a.slug,a.force??!1,{evaluate:a.evaluate??!1,confirmUnevaluated:a.confirm_unevaluated??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_generate=createSwarmTool({description:'Compile mature knowledge entries into a SKILL.md. mode="draft" writes a proposal under .swarm/skills/proposals; mode="active" writes the live skill under .opencode/skills/generated and stamps source entries.',args:{source_knowledge_ids:exports_external.array(exports_external.string()).optional().describe("Optional explicit knowledge ids to compile. If omitted, all mature candidates are clustered and emitted."),slug:exports_external.string().optional().describe("Optional slug for the FIRST cluster. Sanitized; rejected if invalid."),mode:exports_external.enum(["draft","active"]).default("draft"),force:exports_external.boolean().optional().default(!1),evaluate:exports_external.boolean().optional().default(!1).describe("Validate generated skill content against .swarm/skills/evals/<slug> before writing. Default false."),min_confidence:exports_external.number().min(0).max(1).optional(),min_confirmations:exports_external.number().int().min(1).max(50).optional()},execute:async(args2,directory)=>{let a=args2??{},result=await generateSkills({directory,mode:a.mode??"draft",slug:a.slug,sourceKnowledgeIds:a.source_knowledge_ids,force:a.force??!1,evaluate:a.evaluate??!1,minConfidence:a.min_confidence,minConfirmations:a.min_confirmations});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_skill_improver();init_create_tool();var skill_improve=createSwarmTool({description:'Run the skill_improver capability under daily quota. Writes a proposal under .swarm/skill-improver/proposals/<timestamp>.md. With mode="draft_skills" it also drafts SKILL.md proposals for mature clusters. Quota is enforced via .swarm/skill-improver-quota.json.',args:{targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).optional(),mode:exports_external.enum(["proposal","draft_skills"]).optional(),max_calls:exports_external.number().int().min(1).max(100).optional().describe("Override the per-run reservation count (capped by daily max)."),evaluate:exports_external.boolean().optional().default(!1).describe('When mode="draft_skills", validate generated draft skills before writing proposals. Default false.')},execute:async(args2,directory,ctx)=>{let a=args2??{},{config:config3}=loadPluginConfigWithMeta(directory),parsed=SkillImproverConfigSchema.parse(config3.skill_improver??{}),enrichmentConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}).enrichment??{max_calls_per_day:30,quota_window:"utc"};if(!parsed.enabled)return JSON.stringify({ran:!1,reason:'skill_improver is disabled. Set "skill_improver.enabled": true in opencode-swarm config to use this tool.'},null,2);let result=await runSkillImprover({directory,config:parsed,targets:a.targets,mode:a.mode,maxCalls:a.max_calls,sessionId:ctx?.sessionID,enrichmentQuota:{maxCalls:enrichmentConfig.max_calls_per_day,window:enrichmentConfig.quota_window},evaluateDrafts:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_inspect=createSwarmTool({description:"Read a generated skill (active or draft) and return its full markdown body and metadata.",args:{slug:exports_external.string().min(1).describe("Slug of the skill to inspect."),prefer:exports_external.enum(["auto","proposal","active"]).optional().default("auto")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({found:!1,reason:"slug required"});let result=await inspectSkill(directory,a.slug,a.prefer??"auto");return JSON.stringify(result,null,2)}});init_skill_generator();init_create_tool();var skill_list=createSwarmTool({description:"List generated skill drafts (under .swarm/skills/proposals) and active generated skills (under .opencode/skills/generated).",args:{},execute:async(_args,directory)=>{let result=await listSkills(directory);return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_regenerate=createSwarmTool({description:"Regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to regenerate."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate regenerated content against .swarm/skills/evals/<slug> before writing. Default false.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({regenerated:!1,reason:"slug required"});let result=await regenerateSkill(directory,a.slug,{evaluate:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_retire=createSwarmTool({description:"Retire a generated skill by adding a retired.marker file. Retired skills are excluded from scoring and injection.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to retire."),reason:exports_external.string().optional().describe("Optional reason for retirement.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({retired:!1,reason:"slug required"});let result=await retireSkill(directory,a.slug,a.reason);return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_file_locks();init_spec_drift_recovery();init_create_tool();import{mkdir as mkdir57,rename as rename18,writeFile as writeFile28}from"node:fs/promises";import*as path306 from"node:path";var MAX_SPEC_BYTES2=262144,spec_write=createSwarmTool({description:"Write the canonical project spec to .swarm/spec.md. Atomic write, size-bounded (256 KiB), heading-required. Honors spec_writer.allow_spec_write.",args:{content:exports_external.string().min(20).max(MAX_SPEC_BYTES2),mode:exports_external.enum(["replace","append"]).optional().default("replace")},execute:async(args2,directory)=>{let a=args2??{},content=a.content,mode=a.mode??"replace";if(typeof content!=="string"||content.length<20)return JSON.stringify({written:!1,reason:"content must be a string >=20 chars"});if(content.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:`content exceeds ${MAX_SPEC_BYTES2} bytes`});let{config:config3}=loadPluginConfigWithMeta(directory);if(!SpecWriterConfigSchema.parse(config3.spec_writer??{}).allow_spec_write)return JSON.stringify({written:!1,reason:"spec_writer.allow_spec_write is false"},null,2);if(content.indexOf("\x00")!==-1)return JSON.stringify({written:!1,reason:"content contains null byte"},null,2);if(!/^#\s+/m.test(content))return JSON.stringify({written:!1,reason:'spec must contain at least one top-level "# Heading"'},null,2);let specLock=await tryAcquireLock(directory,"spec.md","spec-write",`spec-write-${Date.now()}`);if(!specLock.acquired)return JSON.stringify({written:!1,reason:"another canonical spec write or drift recovery is in progress; retry shortly"},null,2);try{let target=path306.join(directory,".swarm","spec.md");await mkdir57(path306.dirname(target),{recursive:!0});let tmp=`${target}.tmp-${process.pid}-${Date.now()}`,finalContent=content;if(mode==="append")try{if(finalContent=`${(await(await import("node:fs/promises")).readFile(target,"utf-8")).replace(/\s+$/,"")}
|
|
6806
6807
|
|
|
6807
6808
|
${content}
|
|
6808
|
-
`,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}await writeFile28(tmp,finalContent,"utf-8"),await rename18(tmp,target);let specDriftRecovery;try{specDriftRecovery=await reconcileSpecDrift(directory,{mode:"repair",actor:"spec_write",specLockAlreadyHeld:!0})}catch(error93){specDriftRecovery={status:"failed",mode:"repair",message:`Spec write succeeded, but spec drift recovery failed: ${error93 instanceof Error?error93.message:String(error93)}`}}return JSON.stringify({written:!0,path:target,bytes:finalContent.length,spec_drift_recovery:specDriftRecovery},null,2)}finally{if(specLock.lock._release)await specLock.lock._release().catch(()=>{})}}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync161}from"node:fs";import{readdir as readdir21,readFile as readFile55}from"node:fs/promises";import{join as join247}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals233.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath3=_internals233.resolveSwarmKnowledgePath(directory),hivePath=_internals233.resolveHiveKnowledgePath();try{let swarmEntries=await _internals233.readKnowledge(swarmPath3);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals233.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join247(directory,".opencode","skills","generated"),join247(directory,".swarm","skills","proposals")]){if(!_internals233.existsSync(dir))continue;let entries=await _internals233.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join247(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join247(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path307,isProposal}of skillEntries){let skillMdPath=isProposal?path307:join247(path307,"SKILL.md");if(!_internals233.existsSync(skillMdPath))continue;let content=await _internals233.readFile(skillMdPath,"utf-8"),sourceIds=_internals233.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join247(path307,"stale.marker");if(_internals233.existsSync(markerPath))try{await _internals233.clearSkillStale(path307),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals233.retireOrMarkStale(directory,path307,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals233={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath:resolveHiveKnowledgePath2,readdir:readdir21,readFile:readFile55,existsSync:existsSync161};init_zod();init_loader();import{existsSync as existsSync162,mkdirSync as mkdirSync75,readFileSync as readFileSync131,renameSync as renameSync38,unlinkSync as unlinkSync37,writeFileSync as writeFileSync49}from"node:fs";import path307 from"node:path";init_config2();init_gateway();init_reward_capture();init_logger();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();var ALL_MEMBERS2=["critic","reviewer","sme","test_engineer","explorer"],FindingSchema2=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema2=exports_external.object({agent:exports_external.enum(ALL_MEMBERS2),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema2),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected phase council verdicts. The server owns the current round; roundNumber is only an optional expectation. Writes phase-council evidence after durable attempt-state preflight. Architect-only and config-gated.",args:{phaseNumber:ArgsSchema4.shape.phaseNumber.describe("Phase number being reviewed"),swarmId:ArgsSchema4.shape.swarmId.describe("Swarm identifier"),phaseSummary:ArgsSchema4.shape.phaseSummary.describe("Phase summary"),roundNumber:ArgsSchema4.shape.roundNumber.describe("Optional expected server round. Omit to use the authoritative round."),verdicts:ArgsSchema4.shape.verdicts.describe("Collected member verdicts"),working_directory:ArgsSchema4.shape.working_directory.describe("Explicit project root directory"),provenanceAgentName:ArgsSchema4.shape.provenanceAgentName.describe("Optional evidence producer name"),provenanceSessionId:ArgsSchema4.shape.provenanceSessionId.describe("Optional evidence producer session")},async execute(args2,directory,ctx){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"phase","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse2(parsed.error.issues);let input=parsed.data,resolved=resolveWorkingDirectory(input.working_directory,directory);if(!resolved.success)return await recordUnscopedCouncilAttempt(directory,"phase","invalid_working_directory",input,[],ctx?.sessionID)??JSON.stringify({success:!1,reason:resolved.message},null,2);let workingDir=resolved.directory,config3=loadPluginConfig(workingDir),councilConfig=config3.council,distinctMembers=new Set(input.verdicts.map((verdict)=>verdict.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS2.filter((member)=>!distinctMembers.has(member));return runCouncilAttempt({directory:workingDir,scope:{kind:"phase",phaseNumber:input.phaseNumber},clientRound:input.roundNumber,maxRounds:councilConfig?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasPhaseEvidenceAttempt(workingDir,input.phaseNumber,attemptId,round),evaluate:async(authoritativeRound)=>{if(!councilConfig?.enabled)return{disposition:"council_disabled",response:{success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},transition:"stay",gateEffect:"none"};let effectiveMinimum=councilConfig.requireAllMembers?5:councilConfig.minimumMembers??3;if(membersVoted.length<effectiveMinimum)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum}. Members absent: [${membersAbsent.join(", ")}].`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},transition:"stay",gateEffect:"none"};let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,authoritativeRound,councilConfig,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Address every requiredFix and resubmit the phase council."},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length};let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,concernsAllowed=councilConfig.phaseConcernsAllowComplete??!0,transition=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&concernsAllowed?"close":"advance";return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},transition,gateEffect:transition==="close"?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>writePhaseCouncilEvidence(workingDir,synthesis,provenance,attemptId)},afterCommit:async()=>applyPhaseCouncilReward(workingDir,synthesis,config3,ctx)}}})}});function invalidResponse2(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function applyPhaseCouncilReward(workingDir,synthesis,config3,ctx){try{let memoryConfig=config3.memory;if(memoryConfig?.enabled!==!0||!ctx?.sessionID)return;let provider=createConfiguredMemoryProvider(workingDir,memoryConfig);try{let summary={scope:"phase",phaseNumber:synthesis.phaseNumber,overallVerdict:synthesis.overallVerdict,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,roundNumber:synthesis.roundNumber,quorumSize:synthesis.quorumSize},verdictSynthesisJson=JSON.stringify(summary),cap2=memoryConfig.qLearning.verdictPayloadCapBytes;if(typeof cap2==="number"&&cap2>0&&verdictSynthesisJson.length>cap2)verdictSynthesisJson=JSON.stringify(truncateObjectForJson(summary,cap2));await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,verdictSynthesisJson,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}catch(error93){warn(`[submit-phase-council-verdicts] phase council reward capture failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}function phaseEvidencePath2(workingDir,phaseNumber){return path307.join(workingDir,".swarm","evidence",String(phaseNumber),"phase-council.json")}function hasPhaseEvidenceAttempt(workingDir,phaseNumber,attemptId,round){try{let parsed=JSON.parse(readFileSync131(phaseEvidencePath2(workingDir,phaseNumber),"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="phase-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}async function writePhaseCouncilEvidence(workingDir,synthesis,provenance,attemptId){let evidenceFile=phaseEvidencePath2(workingDir,synthesis.phaseNumber);mkdirSync75(path307.dirname(evidenceFile),{recursive:!0});let content={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes,advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,attemptId,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync49(tempFile,JSON.stringify(content,null,2),"utf8"),renameSync38(tempFile,evidenceFile),invalidateCachedArtifact(evidenceFile)}finally{if(existsSync162(tempFile))unlinkSync37(tempFile)}}function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path307.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json"),mutationGateLocation=`.swarm/evidence/${phaseNumber}/mutation-gate.json`;try{let entry=JSON.parse(readFileSync131(mutationGatePath,"utf8")).entries?.find((candidate2)=>candidate2.type==="mutation-gate");if(!entry)return mutationFinding("HIGH",mutationGateLocation,"Mutation gate evidence is missing a mutation-gate entry.");if(entry.verdict==="skip")return mutationFinding("MEDIUM",mutationGateLocation,"Mutation testing was skipped.");if(entry.verdict==="warn")return mutationFinding("LOW",mutationGateLocation,"Mutation gate reported WARN.");if(entry.verdict==="fail")return mutationFinding("HIGH",mutationGateLocation,"Mutation gate reported FAIL.");return null}catch(error93){let missing=error93.code==="ENOENT";return mutationFinding(missing?"HIGH":"MEDIUM",mutationGateLocation,missing?"Mutation gate evidence is missing.":"Mutation gate evidence could not be read.",error93 instanceof Error?error93.message:String(error93))}}function mutationFinding(severity,location,detail,evidence2=detail){return{severity,category:"mutation_gap",location,detail,evidence:evidence2}}function addMutationGapFindingToSynthesis(synthesis,finding){if(["CRITICAL","HIGH","MEDIUM"].includes(finding.severity))synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=`
|
|
6809
|
+
`,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}await writeFile28(tmp,finalContent,"utf-8"),await rename18(tmp,target);let specDriftRecovery;try{specDriftRecovery=await reconcileSpecDrift(directory,{mode:"repair",actor:"spec_write",specLockAlreadyHeld:!0})}catch(error93){specDriftRecovery={status:"failed",mode:"repair",message:`Spec write succeeded, but spec drift recovery failed: ${error93 instanceof Error?error93.message:String(error93)}`}}return JSON.stringify({written:!0,path:target,bytes:finalContent.length,spec_drift_recovery:specDriftRecovery},null,2)}finally{if(specLock.lock._release)await specLock.lock._release().catch(()=>{})}}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync162}from"node:fs";import{readdir as readdir21,readFile as readFile55}from"node:fs/promises";import{join as join247}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals233.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath3=_internals233.resolveSwarmKnowledgePath(directory),hivePath=_internals233.resolveHiveKnowledgePath();try{let swarmEntries=await _internals233.readKnowledge(swarmPath3);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals233.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join247(directory,".opencode","skills","generated"),join247(directory,".swarm","skills","proposals")]){if(!_internals233.existsSync(dir))continue;let entries=await _internals233.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join247(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join247(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path307,isProposal}of skillEntries){let skillMdPath=isProposal?path307:join247(path307,"SKILL.md");if(!_internals233.existsSync(skillMdPath))continue;let content=await _internals233.readFile(skillMdPath,"utf-8"),sourceIds=_internals233.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join247(path307,"stale.marker");if(_internals233.existsSync(markerPath))try{await _internals233.clearSkillStale(path307),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals233.retireOrMarkStale(directory,path307,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals233={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath:resolveHiveKnowledgePath2,readdir:readdir21,readFile:readFile55,existsSync:existsSync162};init_zod();init_loader();import{existsSync as existsSync163,mkdirSync as mkdirSync75,readFileSync as readFileSync131,renameSync as renameSync38,unlinkSync as unlinkSync37,writeFileSync as writeFileSync49}from"node:fs";import path307 from"node:path";init_config2();init_gateway();init_reward_capture();init_logger();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();var ALL_MEMBERS2=["critic","reviewer","sme","test_engineer","explorer"],FindingSchema2=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema2=exports_external.object({agent:exports_external.enum(ALL_MEMBERS2),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema2),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected phase council verdicts. The server owns the current round; roundNumber is only an optional expectation. Writes phase-council evidence after durable attempt-state preflight. Architect-only and config-gated.",args:{phaseNumber:ArgsSchema4.shape.phaseNumber.describe("Phase number being reviewed"),swarmId:ArgsSchema4.shape.swarmId.describe("Swarm identifier"),phaseSummary:ArgsSchema4.shape.phaseSummary.describe("Phase summary"),roundNumber:ArgsSchema4.shape.roundNumber.describe("Optional expected server round. Omit to use the authoritative round."),verdicts:ArgsSchema4.shape.verdicts.describe("Collected member verdicts"),working_directory:ArgsSchema4.shape.working_directory.describe("Explicit project root directory"),provenanceAgentName:ArgsSchema4.shape.provenanceAgentName.describe("Optional evidence producer name"),provenanceSessionId:ArgsSchema4.shape.provenanceSessionId.describe("Optional evidence producer session")},async execute(args2,directory,ctx){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"phase","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse2(parsed.error.issues);let input=parsed.data,resolved=resolveWorkingDirectory(input.working_directory,directory);if(!resolved.success)return await recordUnscopedCouncilAttempt(directory,"phase","invalid_working_directory",input,[],ctx?.sessionID)??JSON.stringify({success:!1,reason:resolved.message},null,2);let workingDir=resolved.directory,config3=loadPluginConfig(workingDir),councilConfig=config3.council,distinctMembers=new Set(input.verdicts.map((verdict)=>verdict.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS2.filter((member)=>!distinctMembers.has(member));return runCouncilAttempt({directory:workingDir,scope:{kind:"phase",phaseNumber:input.phaseNumber},clientRound:input.roundNumber,maxRounds:councilConfig?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasPhaseEvidenceAttempt(workingDir,input.phaseNumber,attemptId,round),evaluate:async(authoritativeRound)=>{if(!councilConfig?.enabled)return{disposition:"council_disabled",response:{success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},transition:"stay",gateEffect:"none"};let effectiveMinimum=councilConfig.requireAllMembers?5:councilConfig.minimumMembers??3;if(membersVoted.length<effectiveMinimum)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum}. Members absent: [${membersAbsent.join(", ")}].`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},transition:"stay",gateEffect:"none"};let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,authoritativeRound,councilConfig,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Address every requiredFix and resubmit the phase council."},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length};let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,concernsAllowed=councilConfig.phaseConcernsAllowComplete??!0,transition=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&concernsAllowed?"close":"advance";return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},transition,gateEffect:transition==="close"?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:membersVoted.length,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>writePhaseCouncilEvidence(workingDir,synthesis,provenance,attemptId)},afterCommit:async()=>applyPhaseCouncilReward(workingDir,synthesis,config3,ctx)}}})}});function invalidResponse2(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function applyPhaseCouncilReward(workingDir,synthesis,config3,ctx){try{let memoryConfig=config3.memory;if(memoryConfig?.enabled!==!0||!ctx?.sessionID)return;let provider=createConfiguredMemoryProvider(workingDir,memoryConfig);try{let summary={scope:"phase",phaseNumber:synthesis.phaseNumber,overallVerdict:synthesis.overallVerdict,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,roundNumber:synthesis.roundNumber,quorumSize:synthesis.quorumSize},verdictSynthesisJson=JSON.stringify(summary),cap2=memoryConfig.qLearning.verdictPayloadCapBytes;if(typeof cap2==="number"&&cap2>0&&verdictSynthesisJson.length>cap2)verdictSynthesisJson=JSON.stringify(truncateObjectForJson(summary,cap2));await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,verdictSynthesisJson,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}catch(error93){warn(`[submit-phase-council-verdicts] phase council reward capture failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}function phaseEvidencePath2(workingDir,phaseNumber){return path307.join(workingDir,".swarm","evidence",String(phaseNumber),"phase-council.json")}function hasPhaseEvidenceAttempt(workingDir,phaseNumber,attemptId,round){try{let parsed=JSON.parse(readFileSync131(phaseEvidencePath2(workingDir,phaseNumber),"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="phase-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}async function writePhaseCouncilEvidence(workingDir,synthesis,provenance,attemptId){let evidenceFile=phaseEvidencePath2(workingDir,synthesis.phaseNumber);mkdirSync75(path307.dirname(evidenceFile),{recursive:!0});let content={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes,advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,attemptId,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync49(tempFile,JSON.stringify(content,null,2),"utf8"),renameSync38(tempFile,evidenceFile),invalidateCachedArtifact(evidenceFile)}finally{if(existsSync163(tempFile))unlinkSync37(tempFile)}}function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path307.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json"),mutationGateLocation=`.swarm/evidence/${phaseNumber}/mutation-gate.json`;try{let entry=JSON.parse(readFileSync131(mutationGatePath,"utf8")).entries?.find((candidate2)=>candidate2.type==="mutation-gate");if(!entry)return mutationFinding("HIGH",mutationGateLocation,"Mutation gate evidence is missing a mutation-gate entry.");if(entry.verdict==="skip")return mutationFinding("MEDIUM",mutationGateLocation,"Mutation testing was skipped.");if(entry.verdict==="warn")return mutationFinding("LOW",mutationGateLocation,"Mutation gate reported WARN.");if(entry.verdict==="fail")return mutationFinding("HIGH",mutationGateLocation,"Mutation gate reported FAIL.");return null}catch(error93){let missing=error93.code==="ENOENT";return mutationFinding(missing?"HIGH":"MEDIUM",mutationGateLocation,missing?"Mutation gate evidence is missing.":"Mutation gate evidence could not be read.",error93 instanceof Error?error93.message:String(error93))}}function mutationFinding(severity,location,detail,evidence2=detail){return{severity,category:"mutation_gap",location,detail,evidence:evidence2}}function addMutationGapFindingToSynthesis(synthesis,finding){if(["CRITICAL","HIGH","MEDIUM"].includes(finding.severity))synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=`
|
|
6809
6810
|
|
|
6810
6811
|
### Mutation Coverage Gap
|
|
6811
6812
|
- **[${finding.severity}]** \`${finding.location}\` (${finding.category}) — ${finding.detail}
|