opencode-swarm 7.164.3 → 7.164.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{coder-settlement-m918n7qj.js → coder-settlement-zzy2egsx.js} +11 -11
- package/dist/cli/{config-doctor-5kytbwbx.js → config-doctor-62xd5far.js} +2 -2
- package/dist/cli/{core-anw5khk2.js → core-7kdmc7h9.js} +1 -1
- package/dist/cli/{curation-policy-7pnmnfct.js → curation-policy-913dnxqq.js} +6 -6
- package/dist/cli/{curator-yq6raqgs.js → curator-4s6ekk85.js} +34 -34
- package/dist/cli/{curator-drift-ykrdf08r.js → curator-drift-3s3q4wsy.js} +4 -4
- package/dist/cli/curator-llm-factory-q3t3r632.js +66 -0
- package/dist/cli/{evidence-summary-service-8sbxvt2x.js → evidence-summary-service-gw936xgz.js} +15 -15
- package/dist/cli/{gate-evidence-53v7e938.js → gate-evidence-4we18rhr.js} +7 -7
- package/dist/cli/guardrail-explain-jjbnrcqn.js +67 -0
- package/dist/cli/{guardrail-log-q5sj7zby.js → guardrail-log-9d4f09qt.js} +7 -7
- package/dist/cli/{guardrail-reset-dw45p5zc.js → guardrail-reset-1hpd6bkj.js} +34 -34
- package/dist/cli/{hive-promoter-0axzw0h5.js → hive-promoter-nr8dsxhe.js} +34 -34
- package/dist/cli/{index-9pwa798m.js → index-08e6x59x.js} +7 -7
- package/dist/cli/{index-jwc2v92w.js → index-0m94jsss.js} +5 -5
- package/dist/cli/{index-hcn69kp0.js → index-0zbze3n6.js} +1 -1
- package/dist/cli/{index-y2f5s2cf.js → index-1f4nandk.js} +1 -1
- package/dist/cli/{index-88g6q52x.js → index-4tgtbptw.js} +4 -4
- package/dist/cli/{index-zs1jrsta.js → index-5k226hxp.js} +2 -2
- package/dist/cli/{index-95hhrw1d.js → index-7zbk1e24.js} +9 -9
- package/dist/cli/{index-kn0y788q.js → index-8fjx6k2s.js} +1 -1
- package/dist/cli/{index-3fpqmms2.js → index-a0jhxx5q.js} +3 -3
- package/dist/cli/{index-kyayzfxp.js → index-cf54ftj1.js} +4 -4
- package/dist/cli/{index-0e34njnm.js → index-eh2k07pp.js} +7 -7
- package/dist/cli/{index-aaqzcnb9.js → index-et9y4ga8.js} +36 -36
- package/dist/cli/{index-yep24wn4.js → index-gt6p21cs.js} +1 -1
- package/dist/cli/{index-w5jpjaqe.js → index-jba9jgse.js} +2 -2
- package/dist/cli/{index-bzd67m2j.js → index-k1m9214q.js} +1 -1
- package/dist/cli/{index-aty2dfmt.js → index-k8vy89vm.js} +1 -1
- package/dist/cli/{index-11st3tgy.js → index-ne38vr77.js} +2 -2
- package/dist/cli/{index-5pxdtskj.js → index-nwpg81ke.js} +1 -1
- package/dist/cli/{index-sb4eanpv.js → index-prammvxb.js} +1 -1
- package/dist/cli/{index-8t11vcf5.js → index-pztdbtgw.js} +3 -3
- package/dist/cli/{index-sn2vm710.js → index-q9yz8da4.js} +5 -5
- package/dist/cli/{index-5d7bzpfn.js → index-qfrrcdhj.js} +1 -1
- package/dist/cli/{index-ehf0vjhx.js → index-qkwx4rrc.js} +71 -71
- package/dist/cli/{index-v56mhyhs.js → index-rz87mx1c.js} +1 -1
- package/dist/cli/{index-ac39znep.js → index-stj85yx1.js} +2 -2
- package/dist/cli/{index-fc153g7b.js → index-t2tqbq62.js} +4 -4
- package/dist/cli/{index-f9nfknjg.js → index-tfa2p4y4.js} +3 -3
- package/dist/cli/{index-c8k4cs94.js → index-tme2kjvq.js} +5 -5
- package/dist/cli/{index-j98116cx.js → index-v7a8e7rv.js} +2 -2
- package/dist/cli/{index-4wneygfx.js → index-vx28633q.js} +1 -1
- package/dist/cli/{index-493mxwj5.js → index-vzs3st30.js} +21 -21
- package/dist/cli/{index-84qah5h6.js → index-wzmchqry.js} +1 -1
- package/dist/cli/{index-xkqja15t.js → index-x63jqvj3.js} +2 -2
- package/dist/cli/{index-2xj34nkh.js → index-x9ayhkkx.js} +1 -1
- package/dist/cli/{index-qbr05tbw.js → index-xj4kbtdw.js} +2 -2
- package/dist/cli/{index-rhdwrfgc.js → index-xjw7j7et.js} +5 -5
- package/dist/cli/{index-yhpbcrdk.js → index-yx3xqb0w.js} +13 -13
- package/dist/cli/{index-0145kpjr.js → index-z408nj03.js} +2 -2
- package/dist/cli/index.js +34 -34
- package/dist/cli/{knowledge-escalator-atn5tfy2.js → knowledge-escalator-hp1ctjpe.js} +13 -13
- package/dist/cli/{knowledge-events-58ha93tx.js → knowledge-events-0qrenmng.js} +11 -11
- package/dist/cli/{knowledge-link-2gh1cnk3.js → knowledge-link-f5g5d171.js} +5 -5
- package/dist/cli/{knowledge-store-2vkn4qyy.js → knowledge-store-8er824g9.js} +6 -6
- package/dist/cli/{knowledge-validator-gcbfq9er.js → knowledge-validator-0jd3htcj.js} +8 -8
- package/dist/cli/{pending-delegations-esp3gpac.js → pending-delegations-d1n5faxg.js} +6 -6
- package/dist/cli/{pr-subscriptions-sdv0n59c.js → pr-subscriptions-s2b2yvbd.js} +6 -6
- package/dist/cli/{pr-workflow-gate-v5wh09wz.js → pr-workflow-gate-51s842yy.js} +34 -34
- package/dist/cli/{runner-m95v9d47.js → runner-nkh65pcm.js} +6 -6
- package/dist/cli/{scan-cursor-6x0sqjer.js → scan-cursor-gt55f3d6.js} +7 -7
- package/dist/cli/{schema-mgpsycrr.js → schema-rpdz901j.js} +1 -1
- package/dist/cli/{scope-persistence-pwqshfyr.js → scope-persistence-js1ywq04.js} +9 -9
- package/dist/cli/{skill-generator-bywdfza0.js → skill-generator-xsxes2w0.js} +15 -15
- package/dist/cli/{telemetry-c4j18da8.js → telemetry-9tfts5q2.js} +1 -1
- package/dist/cli/{worktree-collision-ownership-71x5pqfz.js → worktree-collision-ownership-54ca6mb8.js} +7 -7
- package/dist/cli/{worktree-isolation-e6tym281.js → worktree-isolation-haesnft8.js} +34 -34
- package/dist/config/plan-schema.d.ts +1 -1
- package/dist/council/council-review-identity.d.ts +1 -1
- package/dist/index.js +15 -15
- package/dist/plan/ledger.d.ts +56 -29
- package/dist/services/skill-optimizer/store.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cli/curator-llm-factory-6swjnnb1.js +0 -66
- package/dist/cli/guardrail-explain-jhsqdzxr.js +0 -67
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.164.3",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/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","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","schema:generate":"bun run scripts/generate-config-schema.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:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:registry-citations":"bun run scripts/check-registry-citations.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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; 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,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.164.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/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","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","schema:generate":"bun run scripts/generate-config-schema.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:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:registry-citations":"bun run scripts/check-registry-citations.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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; 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,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -185,7 +185,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
185
185
|
`),totalLines=lines.length,startLine=Math.max(0,offset);if(startLine>=totalLines)return{totalLines,startLine,endLine:totalLines,content:"",exhausted:!0};let endLine=Math.min(startLine+limit,totalLines);return{totalLines,startLine,endLine,content:lines.slice(startLine,endLine).join(`
|
|
186
186
|
`),exhausted:!1}}function buildPreviewMarker(args2){let retrieval=args2.ref?` retrieve_lane_output ref=${args2.ref} for full output.`:" no full output artifact is available; treat this lane as degraded.";return`
|
|
187
187
|
[... lane output preview omitted middle content.${args2.degraded?" Artifact storage degraded.":""}${retrieval} ...]
|
|
188
|
-
`}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path8.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync2(path8.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync3(tempFile))try{unlinkSync(tempFile)}catch{}}}function digestText(text){return createHash3("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});import*as crypto2 from"node:crypto";import*as fs5 from"node:fs";import*as path9 from"node:path";function getLockFilePath(directory,filePath){let normalized=path9.resolve(directory,filePath),baseDir=path9.resolve(directory)+path9.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path9.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path9.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs5.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals8.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs5.promises.rename(tmpPath,metaPath)}catch(err){try{await fs5.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs5.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path9.dirname(lockPath);if(!fs5.existsSync(locksDir))fs5.mkdirSync(locksDir,{recursive:!0});if(!fs5.existsSync(lockPath))fs5.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs5.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path9.join(directory,LOCKS_DIR),locks=[];if(!fs5.existsSync(locksDir))return locks;let files=fs5.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path9.join(locksDir,file2);try{if(fs5.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs5.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs5.unlinkSync(metaPath2)}catch{}try{fs5.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs5.unlinkSync(mp)}catch{}try{fs5.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs5.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path9.join(directory,LOCKS_DIR);if(!fs5.existsSync(locksDir))return 0;let files=fs5.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path9.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs5.unlinkSync(lockPath)}catch{}try{fs5.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals8;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals8={tryAcquireLock,writeFile:fs5.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:429"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:426"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:413"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:232"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:550",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:554",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:558",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:596",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:644",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:826",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:834",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:859",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:562",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:572",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:642",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1567",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1587",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:605",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:622",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:609",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:632",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:648",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:667",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1216",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:705",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:714",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:814",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:822",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:844",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:732",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:753",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:767",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:784",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:801",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:874",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:888",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:901",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:915",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:345",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1853",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1143",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:952",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:974",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:998",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1035",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1061",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1085",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1108",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1137",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1181",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash5,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash5("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals9,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs6 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path10.join(projectDirectory,".swarm");if(!fs6.existsSync(swarmDir))fs6.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path10.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}catch{_disabled=!0,_writeStream=null}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals9.createObservation(event,data),line=JSON.stringify(_internals9.toLegacyTelemetryLine(canonical))+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals9.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs6.existsSync(telemetryPath))return;if(fs6.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs6.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals9;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals9.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals9.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals9.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals9.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals9.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals9.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals9.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals9.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals9.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals9.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals9.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals9.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals9.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals9.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals9.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals9.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals9.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals9.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals9.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals9.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals9.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals9.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals9.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals9.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals9.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals9.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals9.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals9.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals9.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals9.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals9.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals9.emit("close_archive_result",data)},residueHealth(data){_internals9.emit("residue_health",data)},contextTelemetryHealth(data){_internals9.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals9.emit("skill_usage_health",data)},coreEventsHealth(data){_internals9.emit("core_events_health",data)},shellAuditHealth(data){_internals9.emit("shell_audit_health",data)},trajectoryHealth(data){_internals9.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals9.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals9.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals9.emit("retrieval_routed",{sessionId,...data})}},_internals9={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs7 from"node:fs";import*as os4 from"node:os";import*as path11 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path11.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals10.lstatSync(path11.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path11.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path11.sep}`)&&!path11.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path11.resolve(directory);return resolved===path11.resolve(os4.tmpdir())||resolved===path11.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path11.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs7,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path11.dirname(current);if(parent===current)break;if(path11.dirname(parent)===parent){current=parent;continue}let parentSwarm=path11.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals10;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals10={lstatSync:fs7.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve6)=>setTimeout(resolve6,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as fsSync3 from"node:fs";import*as path12 from"node:path";function resolveCanonicalRootKey(directory){let resolved=path12.resolve(directory);try{resolved=fsSync3.realpathSync(resolved)}catch{}return process.platform==="win32"?resolved.toLowerCase():resolved}function canonicalRootKey(directory){let memoized=canonicalRootMemo.get(directory);if(memoized!==void 0)return memoized;let key=resolveCanonicalRootKey(directory);if(!canonicalRootMemo.has(directory))while(canonicalRootMemo.size>=MAX_CANONICAL_ROOT_CACHE){let oldest=canonicalRootMemo.keys().next().value;if(oldest===void 0)break;canonicalRootMemo.delete(oldest)}return canonicalRootMemo.set(directory,key),key}function canonicalRootKeyFresh(directory){return resolveCanonicalRootKey(directory)}function compositeSessionKey(directory,sessionId){return`${canonicalRootKey(directory)}${SESSION_KEY_SEPARATOR}${sessionId}`}function sessionKeySuffix(sessionId){return`${SESSION_KEY_SEPARATOR}${sessionId}`}var SESSION_KEY_SEPARATOR,canonicalRootMemo,MAX_CANONICAL_ROOT_CACHE=128;var init_canonical_root=__esm(()=>{SESSION_KEY_SEPARATOR=String.fromCharCode(0),canonicalRootMemo=new Map});import{randomBytes as randomBytes2}from"node:crypto";import*as fs8 from"node:fs";import*as path13 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path13.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs8.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path13.normalize(path13.resolve(targetPath)),segments=resolved.split(path13.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path13.sep);try{let st=fs8.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path13.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path13.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path13.sep)){if(probe=path13.join(probe,seg),!fs8.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path13.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals11.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path13.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals11.randomSuffix()}.tmp`;fs8.mkdirSync(path13.dirname(tempPath),{recursive:!0});try{let fd=fs8.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals11.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals11.fsyncSync(fd)}catch{}}finally{fs8.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals11.unlinkSync(tempPath)}catch{}}try{let dirFd=fs8.openSync(path13.dirname(resolvedTarget),"r");try{fs8.fsyncSync(dirFd)}finally{fs8.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve8)=>setImmediate(resolve8)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve8)=>setImmediate(resolve8)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals11;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:250"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migration extracted to src/pr-review/persistence.ts)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:493","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1091","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:140","src/tools/write-pr-review-artifact.ts:160","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:109","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals11={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs8.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs8.renameSync(from,to),unlinkSync:(p)=>fs8.unlinkSync(p),fsyncSync:(fd)=>fs8.fsyncSync(fd)}});import{promises as fs9}from"node:fs";import path14 from"node:path";function rememberPersistDirectory(directory){if(recentPersistDirectories.includes(directory)){let idx=recentPersistDirectories.indexOf(directory);recentPersistDirectories.splice(idx,1)}recentPersistDirectories.push(directory);while(recentPersistDirectories.length>MAX_TRACKED_DIRECTORIES){let evicted=recentPersistDirectories.shift();if(evicted!==void 0)lastPersistAtByDirectory.delete(evicted)}}function projectRef(directory){let cached2=projectRefCache.get(directory);if(cached2!==void 0)return cached2;let ref=pseudonymousRef(directory,resolveLineageSalt());if(!projectRefCache.has(directory))while(projectRefCache.size>=MAX_TRACKED_DIRECTORIES){let oldest=projectRefCache.keys().next().value;if(oldest===void 0)break;projectRefCache.delete(oldest)}return projectRefCache.set(directory,ref),ref}function sessionScopeKey(directory,sessionID){let ref=pseudonymousSessionRef(sessionID);return directory?`${projectRef(directory)}/${ref}`:`u/${ref}`}function getScopeMap(alarm){let map2=alarmScopes.get(alarm);if(!map2)map2=new Map,alarmScopes.set(alarm,map2);return map2}function ensureScope(alarm,scopeKey,now){let map2=getScopeMap(alarm),scope=map2.get(scopeKey);if(scope)return scope;while(map2.size>=MAX_HEALTH_SCOPES){let oldest=map2.keys().next().value;if(oldest===void 0)break;if(oldest===scopeKey)break;map2.delete(oldest)}return scope={status:"idle",severity:LEARNING_HEALTH_ALARM_CONFIG[alarm].severity,windowStartMs:now,factCount:0,lastFactAtMs:0,raisedAtMs:0,lastEmitAtMs:0,transitionCount:0,facts:[]},map2.set(scopeKey,scope),scope}function appendFact(scope,kind,atMs,windowMs){if(!scope.facts.some((f)=>f.kind===kind&&f.atMs===atMs)){scope.facts.push({atMs,kind});while(scope.facts.length>MAX_FACTS_PER_SCOPE)scope.facts.shift()}let skewAdjusted=Math.min(atMs,_internals12.now()+CLOCK_SKEW_TOLERANCE_MS);if(scope.lastFactAtMs=Math.max(scope.lastFactAtMs,skewAdjusted),skewAdjusted-scope.windowStartMs>windowMs){let edge=skewAdjusted-windowMs;scope.facts=scope.facts.filter((f)=>f.atMs>=edge),scope.windowStartMs=edge}scope.factCount=scope.facts.length}function countFacts(scope,kind){let n=0;for(let fact of scope.facts)if(fact.kind===kind)n+=1;return n}function emitTransition(alarm,scopeClass,scopeKey,transition,severity,detail,scope,now){scope.lastEmitAtMs=now,scope.transitionCount+=1;let payload={alarm,transition,severity,scope_class:scopeClass,window_ms:LEARNING_HEALTH_ALARM_CONFIG[alarm].windowMs,coverage_facts:scope.factCount,raise_facts:scope.raisedAtMs>0?countRaiseFacts(alarm,scope):0,age_ms:scope.raisedAtMs>0?Math.max(0,now-scope.raisedAtMs):0};if(scopeClass==="session")payload.session_ref=scopeKey.split("/").pop();for(let[key,value]of Object.entries(detail)){if(value===void 0)continue;let payloadKey=DETAIL_PAYLOAD_KEYS[key]??key;payload[payloadKey]=value}transitionRing.push({alarm,transition,severity,atMs:now,coverageFacts:scope.factCount});while(transitionRing.length>MAX_TRANSITION_RING)transitionRing.shift();_internals12.emitTelemetry(payload)}function countRaiseFacts(alarm,scope){switch(alarm){case"headroom_dead_streak":return countFacts(scope,"dead");case"role_participation":return countFacts(scope,"gap");case"promoted_fixture_share":return countFacts(scope,"non_field");case"compaction_drop_coverage":return countFacts(scope,"corrupt")+countFacts(scope,"dropped");default:return scope.factCount}}function applyAlarmState(alarm,scopeClass,scopeKey,desired,severity,detail,directory,now){if(directory)rememberPersistDirectory(directory);let scope=ensureScope(alarm,scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG[alarm];if(desired==="active"){if(scope.severity=severity,scope.status==="idle")scope.status="active",scope.raisedAtMs=now,emitTransition(alarm,scopeClass,scopeKey,"raised",severity,detail,scope,now),schedulePersist(directory,now,!0);else if(now-scope.lastEmitAtMs>=config2.cooldownMs)emitTransition(alarm,scopeClass,scopeKey,"sustained",severity,detail,scope,now),schedulePersist(directory,now,!0);return}if(scope.status==="active")scope.status="idle",scope.severity=LEARNING_HEALTH_ALARM_CONFIG[alarm].severity,emitTransition(alarm,scopeClass,scopeKey,"recovered",severity,detail,scope,now),schedulePersist(directory,now,!0)}function schedulePersist(directory,now,force){let target=directory??recentPersistDirectories.at(-1);if(!target)return;let last=lastPersistAtByDirectory.get(target)??0;if(!force&&now-last<PERSIST_DEBOUNCE_MS)return;lastPersistAtByDirectory.set(target,now),persistLearningHealth(target).catch(()=>{return})}async function persistLearningHealth(directory){let artifact={schemaVersion:ARTIFACT_SCHEMA_VERSION,updatedAtMs:_internals12.now(),alarms:{},transitions:[...transitionRing]};for(let[alarm,scopes]of alarmScopes){if(scopes.size===0)continue;let serialized={};for(let[key,scope]of scopes)serialized[key]={status:scope.status,severity:scope.severity,windowStartMs:scope.windowStartMs,factCount:scope.factCount,lastFactAtMs:scope.lastFactAtMs,raisedAtMs:scope.raisedAtMs,transitionCount:scope.transitionCount};artifact.alarms[alarm]={scopes:serialized}}try{await _internals12.writeArtifact(directory,`${JSON.stringify(artifact)}
|
|
188
|
+
`}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path8.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync2(path8.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync3(tempFile))try{unlinkSync(tempFile)}catch{}}}function digestText(text){return createHash3("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});import*as crypto2 from"node:crypto";import*as fs5 from"node:fs";import*as path9 from"node:path";function getLockFilePath(directory,filePath){let normalized=path9.resolve(directory,filePath),baseDir=path9.resolve(directory)+path9.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path9.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path9.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs5.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals8.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs5.promises.rename(tmpPath,metaPath)}catch(err){try{await fs5.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs5.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path9.dirname(lockPath);if(!fs5.existsSync(locksDir))fs5.mkdirSync(locksDir,{recursive:!0});if(!fs5.existsSync(lockPath))fs5.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs5.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path9.join(directory,LOCKS_DIR),locks=[];if(!fs5.existsSync(locksDir))return locks;let files=fs5.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path9.join(locksDir,file2);try{if(fs5.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs5.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs5.unlinkSync(metaPath2)}catch{}try{fs5.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs5.unlinkSync(mp)}catch{}try{fs5.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs5.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path9.join(directory,LOCKS_DIR);if(!fs5.existsSync(locksDir))return 0;let files=fs5.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path9.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs5.unlinkSync(lockPath)}catch{}try{fs5.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals8;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals8={tryAcquireLock,writeFile:fs5.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:429"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:426"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:413"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:232"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:550",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:554",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:558",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:596",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:644",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:826",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:834",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:859",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:562",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:572",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:642",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1567",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1587",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:605",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:622",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:609",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:632",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:648",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:667",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1216",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:705",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:714",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:718",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:814",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:822",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:844",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:732",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:753",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:767",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:784",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:801",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:874",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:888",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:901",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:915",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:345",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1853",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1167",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:952",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:974",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:998",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1035",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1061",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1085",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1108",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1137",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1181",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash5,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash5("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals9,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs6 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path10.join(projectDirectory,".swarm");if(!fs6.existsSync(swarmDir))fs6.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path10.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}catch{_disabled=!0,_writeStream=null}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals9.createObservation(event,data),line=JSON.stringify(_internals9.toLegacyTelemetryLine(canonical))+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals9.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs6.existsSync(telemetryPath))return;if(fs6.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs6.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals9;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals9.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals9.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals9.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals9.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals9.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals9.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals9.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals9.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals9.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals9.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals9.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals9.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals9.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals9.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals9.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals9.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals9.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals9.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals9.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals9.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals9.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals9.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals9.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals9.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals9.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals9.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals9.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals9.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals9.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals9.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals9.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals9.emit("close_archive_result",data)},residueHealth(data){_internals9.emit("residue_health",data)},contextTelemetryHealth(data){_internals9.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals9.emit("skill_usage_health",data)},coreEventsHealth(data){_internals9.emit("core_events_health",data)},shellAuditHealth(data){_internals9.emit("shell_audit_health",data)},trajectoryHealth(data){_internals9.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals9.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals9.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals9.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals9.emit("retrieval_routed",{sessionId,...data})}},_internals9={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs7 from"node:fs";import*as os4 from"node:os";import*as path11 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path11.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals10.lstatSync(path11.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path11.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path11.sep}`)&&!path11.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path11.resolve(directory);return resolved===path11.resolve(os4.tmpdir())||resolved===path11.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path11.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs7,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path11.dirname(current);if(parent===current)break;if(path11.dirname(parent)===parent){current=parent;continue}let parentSwarm=path11.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals10;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals10={lstatSync:fs7.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve6)=>setTimeout(resolve6,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as fsSync3 from"node:fs";import*as path12 from"node:path";function resolveCanonicalRootKey(directory){let resolved=path12.resolve(directory);try{resolved=fsSync3.realpathSync(resolved)}catch{}return process.platform==="win32"?resolved.toLowerCase():resolved}function canonicalRootKey(directory){let memoized=canonicalRootMemo.get(directory);if(memoized!==void 0)return memoized;let key=resolveCanonicalRootKey(directory);if(!canonicalRootMemo.has(directory))while(canonicalRootMemo.size>=MAX_CANONICAL_ROOT_CACHE){let oldest=canonicalRootMemo.keys().next().value;if(oldest===void 0)break;canonicalRootMemo.delete(oldest)}return canonicalRootMemo.set(directory,key),key}function canonicalRootKeyFresh(directory){return resolveCanonicalRootKey(directory)}function compositeSessionKey(directory,sessionId){return`${canonicalRootKey(directory)}${SESSION_KEY_SEPARATOR}${sessionId}`}function sessionKeySuffix(sessionId){return`${SESSION_KEY_SEPARATOR}${sessionId}`}var SESSION_KEY_SEPARATOR,canonicalRootMemo,MAX_CANONICAL_ROOT_CACHE=128;var init_canonical_root=__esm(()=>{SESSION_KEY_SEPARATOR=String.fromCharCode(0),canonicalRootMemo=new Map});import{randomBytes as randomBytes2}from"node:crypto";import*as fs8 from"node:fs";import*as path13 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path13.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs8.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path13.normalize(path13.resolve(targetPath)),segments=resolved.split(path13.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path13.sep);try{let st=fs8.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path13.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path13.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path13.sep)){if(probe=path13.join(probe,seg),!fs8.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path13.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals11.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path13.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals11.randomSuffix()}.tmp`;fs8.mkdirSync(path13.dirname(tempPath),{recursive:!0});try{let fd=fs8.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals11.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals11.fsyncSync(fd)}catch{}}finally{fs8.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals11.unlinkSync(tempPath)}catch{}}try{let dirFd=fs8.openSync(path13.dirname(resolvedTarget),"r");try{fs8.fsyncSync(dirFd)}finally{fs8.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve8)=>setImmediate(resolve8)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve8)=>setImmediate(resolve8)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals11;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:250"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migration extracted to src/pr-review/persistence.ts)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:629","src/plan/manager.ts:1785","src/plan/manager.ts:1831","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:493","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:737","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1091","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:140","src/tools/write-pr-review-artifact.ts:160","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1971","src/plan/manager.ts:2160"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:109","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1333","src/plan/ledger.ts:1334"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals11={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs8.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs8.renameSync(from,to),unlinkSync:(p)=>fs8.unlinkSync(p),fsyncSync:(fd)=>fs8.fsyncSync(fd)}});import{promises as fs9}from"node:fs";import path14 from"node:path";function rememberPersistDirectory(directory){if(recentPersistDirectories.includes(directory)){let idx=recentPersistDirectories.indexOf(directory);recentPersistDirectories.splice(idx,1)}recentPersistDirectories.push(directory);while(recentPersistDirectories.length>MAX_TRACKED_DIRECTORIES){let evicted=recentPersistDirectories.shift();if(evicted!==void 0)lastPersistAtByDirectory.delete(evicted)}}function projectRef(directory){let cached2=projectRefCache.get(directory);if(cached2!==void 0)return cached2;let ref=pseudonymousRef(directory,resolveLineageSalt());if(!projectRefCache.has(directory))while(projectRefCache.size>=MAX_TRACKED_DIRECTORIES){let oldest=projectRefCache.keys().next().value;if(oldest===void 0)break;projectRefCache.delete(oldest)}return projectRefCache.set(directory,ref),ref}function sessionScopeKey(directory,sessionID){let ref=pseudonymousSessionRef(sessionID);return directory?`${projectRef(directory)}/${ref}`:`u/${ref}`}function getScopeMap(alarm){let map2=alarmScopes.get(alarm);if(!map2)map2=new Map,alarmScopes.set(alarm,map2);return map2}function ensureScope(alarm,scopeKey,now){let map2=getScopeMap(alarm),scope=map2.get(scopeKey);if(scope)return scope;while(map2.size>=MAX_HEALTH_SCOPES){let oldest=map2.keys().next().value;if(oldest===void 0)break;if(oldest===scopeKey)break;map2.delete(oldest)}return scope={status:"idle",severity:LEARNING_HEALTH_ALARM_CONFIG[alarm].severity,windowStartMs:now,factCount:0,lastFactAtMs:0,raisedAtMs:0,lastEmitAtMs:0,transitionCount:0,facts:[]},map2.set(scopeKey,scope),scope}function appendFact(scope,kind,atMs,windowMs){if(!scope.facts.some((f)=>f.kind===kind&&f.atMs===atMs)){scope.facts.push({atMs,kind});while(scope.facts.length>MAX_FACTS_PER_SCOPE)scope.facts.shift()}let skewAdjusted=Math.min(atMs,_internals12.now()+CLOCK_SKEW_TOLERANCE_MS);if(scope.lastFactAtMs=Math.max(scope.lastFactAtMs,skewAdjusted),skewAdjusted-scope.windowStartMs>windowMs){let edge=skewAdjusted-windowMs;scope.facts=scope.facts.filter((f)=>f.atMs>=edge),scope.windowStartMs=edge}scope.factCount=scope.facts.length}function countFacts(scope,kind){let n=0;for(let fact of scope.facts)if(fact.kind===kind)n+=1;return n}function emitTransition(alarm,scopeClass,scopeKey,transition,severity,detail,scope,now){scope.lastEmitAtMs=now,scope.transitionCount+=1;let payload={alarm,transition,severity,scope_class:scopeClass,window_ms:LEARNING_HEALTH_ALARM_CONFIG[alarm].windowMs,coverage_facts:scope.factCount,raise_facts:scope.raisedAtMs>0?countRaiseFacts(alarm,scope):0,age_ms:scope.raisedAtMs>0?Math.max(0,now-scope.raisedAtMs):0};if(scopeClass==="session")payload.session_ref=scopeKey.split("/").pop();for(let[key,value]of Object.entries(detail)){if(value===void 0)continue;let payloadKey=DETAIL_PAYLOAD_KEYS[key]??key;payload[payloadKey]=value}transitionRing.push({alarm,transition,severity,atMs:now,coverageFacts:scope.factCount});while(transitionRing.length>MAX_TRANSITION_RING)transitionRing.shift();_internals12.emitTelemetry(payload)}function countRaiseFacts(alarm,scope){switch(alarm){case"headroom_dead_streak":return countFacts(scope,"dead");case"role_participation":return countFacts(scope,"gap");case"promoted_fixture_share":return countFacts(scope,"non_field");case"compaction_drop_coverage":return countFacts(scope,"corrupt")+countFacts(scope,"dropped");default:return scope.factCount}}function applyAlarmState(alarm,scopeClass,scopeKey,desired,severity,detail,directory,now){if(directory)rememberPersistDirectory(directory);let scope=ensureScope(alarm,scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG[alarm];if(desired==="active"){if(scope.severity=severity,scope.status==="idle")scope.status="active",scope.raisedAtMs=now,emitTransition(alarm,scopeClass,scopeKey,"raised",severity,detail,scope,now),schedulePersist(directory,now,!0);else if(now-scope.lastEmitAtMs>=config2.cooldownMs)emitTransition(alarm,scopeClass,scopeKey,"sustained",severity,detail,scope,now),schedulePersist(directory,now,!0);return}if(scope.status==="active")scope.status="idle",scope.severity=LEARNING_HEALTH_ALARM_CONFIG[alarm].severity,emitTransition(alarm,scopeClass,scopeKey,"recovered",severity,detail,scope,now),schedulePersist(directory,now,!0)}function schedulePersist(directory,now,force){let target=directory??recentPersistDirectories.at(-1);if(!target)return;let last=lastPersistAtByDirectory.get(target)??0;if(!force&&now-last<PERSIST_DEBOUNCE_MS)return;lastPersistAtByDirectory.set(target,now),persistLearningHealth(target).catch(()=>{return})}async function persistLearningHealth(directory){let artifact={schemaVersion:ARTIFACT_SCHEMA_VERSION,updatedAtMs:_internals12.now(),alarms:{},transitions:[...transitionRing]};for(let[alarm,scopes]of alarmScopes){if(scopes.size===0)continue;let serialized={};for(let[key,scope]of scopes)serialized[key]={status:scope.status,severity:scope.severity,windowStartMs:scope.windowStartMs,factCount:scope.factCount,lastFactAtMs:scope.lastFactAtMs,raisedAtMs:scope.raisedAtMs,transitionCount:scope.transitionCount};artifact.alarms[alarm]={scopes:serialized}}try{await _internals12.writeArtifact(directory,`${JSON.stringify(artifact)}
|
|
189
189
|
`)}catch{}}async function rehydrateFromArtifact(directory){let raw=await _internals12.readArtifact(directory);if(!raw)return;let parsed;try{parsed=JSON.parse(raw)}catch{return}if(parsed.schemaVersion!==ARTIFACT_SCHEMA_VERSION)return;let now=_internals12.now();if(transitionRing.length===0&&Array.isArray(parsed.transitions)){for(let tr of parsed.transitions){if(!tr||typeof tr.alarm!=="string"||!Object.hasOwn(LEARNING_HEALTH_ALARM_CONFIG,tr.alarm)||typeof tr.atMs!=="number"||!Number.isFinite(tr.atMs))continue;transitionRing.push({alarm:tr.alarm,transition:tr.transition==="raised"||tr.transition==="sustained"||tr.transition==="recovered"?tr.transition:"raised",severity:tr.severity==="critical"?"critical":"warning",atMs:tr.atMs,coverageFacts:typeof tr.coverageFacts==="number"&&Number.isFinite(tr.coverageFacts)?tr.coverageFacts:0})}while(transitionRing.length>MAX_TRANSITION_RING)transitionRing.shift()}for(let[alarm,section]of Object.entries(parsed.alarms??{})){if(!Object.hasOwn(LEARNING_HEALTH_ALARM_CONFIG,alarm))continue;if(!section?.scopes)continue;let map2=getScopeMap(alarm);for(let[key,persisted]of Object.entries(section.scopes)){if(map2.has(key))continue;if(!isAdoptableScopeKey(key))continue;if(!persisted||persisted.status!=="idle"&&persisted.status!=="active"||persisted.severity!=="warning"&&persisted.severity!=="critical"||!isFiniteCounter(persisted.windowStartMs)||!isFiniteCounter(persisted.factCount)||!isFiniteCounter(persisted.lastFactAtMs)||!isFiniteCounter(persisted.raisedAtMs)||!isFiniteCounter(persisted.transitionCount))continue;map2.set(key,{status:persisted.status,severity:persisted.severity,windowStartMs:persisted.windowStartMs,factCount:persisted.factCount,lastFactAtMs:persisted.lastFactAtMs,raisedAtMs:persisted.raisedAtMs,lastEmitAtMs:now,transitionCount:persisted.transitionCount,facts:[]})}}}function isAdoptableScopeKey(key){if(typeof key!=="string"||key.length===0||key.length>200)return!1;return/^[0-9a-zA-Z:_.-/]+$/.test(key)}function isFiniteCounter(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0}function observeContextHeadroom(input){try{ensureLearningHealth();let now=_internals12.now(),scopeKey=sessionScopeKey(input.directory,input.sessionID),scope=ensureScope("headroom_dead_streak",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.headroom_dead_streak,dead=Number.isFinite(input.usagePercent)&&input.usagePercent>=1,healthy=Number.isFinite(input.usagePercent)&&input.usagePercent<input.warnThreshold;appendFact(scope,dead?"dead":healthy?"healthy":"warm",now,config2.windowMs);let deadFacts=countFacts(scope,"dead"),denominatorFallback=input.limitSource==="provider_cap"||input.limitSource==="native"||input.limitSource==="fallback",detail={limitSource:input.limitSource,denominatorFallback};if(deadFacts>=config2.raiseFacts)applyAlarmState("headroom_dead_streak","session",scopeKey,"active",config2.severity,detail,input.directory,now);else if(healthy)applyAlarmState("headroom_dead_streak","session",scopeKey,"idle",config2.severity,detail,input.directory,now)}catch{}}function observeModelLimitResolution(input){try{ensureLearningHealth();let now=_internals12.now(),identity=input.directory?`${projectRef(input.directory)}/identity/${input.modelID||"unknown"}::${input.providerID||"unknown"}`:`u/identity/${input.modelID||"unknown"}::${input.providerID||"unknown"}`,scope=ensureScope("model_limit_fallback",identity,now),config2=LEARNING_HEALTH_ALARM_CONFIG.model_limit_fallback,fallback=input.resolution==="static_provider_cap"||input.resolution==="static_native"||input.resolution==="static_default";if(appendFact(scope,fallback?"fallback":"resolved",now,config2.windowMs),input.invalidOverride)appendFact(scope,"invalid_override",now,config2.windowMs);let detail={model:input.modelID||"unknown",provider:input.providerID||"unknown",role:input.aliasKeyClass,reason:input.invalidOverride?"invalid_override_skipped":fallback?String(input.resolution):void 0};if(fallback||input.invalidOverride)applyAlarmState("model_limit_fallback","identity",identity,"active",config2.severity,detail,input.directory,now);else applyAlarmState("model_limit_fallback","identity",identity,"idle",config2.severity,detail,input.directory,now)}catch{}}function livenessMap(directory){let map2=livenessGaps.get(directory);if(!map2){if(livenessGaps.size>=MAX_TRACKED_DIRECTORIES){let victim,victimSize=Number.POSITIVE_INFINITY;for(let[dir,entry]of livenessGaps)if(entry.size<victimSize)victim=dir,victimSize=entry.size;if(victim!==void 0)livenessGaps.delete(victim)}map2=new Map,livenessGaps.set(directory,map2)}return map2}function evaluateLiveness(directory,now){let config2=LEARNING_HEALTH_ALARM_CONFIG.retrieval_outcome_liveness,gaps=livenessMap(directory),ageOutAt=config2.windowMs*4;for(let[key,gap]of gaps)if(now-gap.openedAtMs>ageOutAt)gaps.delete(key);let scopeKey=`${projectRef(directory)}/liveness`,_scope=ensureScope("retrieval_outcome_liveness",scopeKey,now),stalled=0,oldestAgeMs=0,stalledType;for(let gap of gaps.values()){if(gap.eligibleAtMs>now)continue;let age=now-gap.openedAtMs;if(age>config2.windowMs){if(stalled+=1,age>oldestAgeMs)oldestAgeMs=age,stalledType=gap.gapType}}if(stalled>0)applyAlarmState("retrieval_outcome_liveness","project",scopeKey,"active",config2.severity,{reason:"gap_open",gapType:stalledType},directory,now);else if(stalled===0&&_scope.status==="active")applyAlarmState("retrieval_outcome_liveness","project",scopeKey,"idle",config2.severity,{},directory,now)}function observeReceiptTransition(input){try{ensureLearningHealth();let now=input.atMs??_internals12.now(),config2=LEARNING_HEALTH_ALARM_CONFIG.retrieval_outcome_liveness,gaps=livenessMap(input.directory),gapKey1=`m:${input.traceId}`,gapKey2=`a:${input.traceId}`;switch(input.kind){case"membership_committed":{if(!gaps.get(gapKey1)){while(gaps.size>=MAX_LIVENESS_GAPS){let oldest=gaps.keys().next().value;if(oldest===void 0)break;gaps.delete(oldest)}gaps.set(gapKey1,{gapType:"membership_to_terminal",openedAtMs:now,eligibleAtMs:now})}break}case"legacy_imported":break;case"terminal_committed":{if(gaps.delete(gapKey1),input.receiptOutcome==="applied"){let committedAt=input.membershipCommittedAtMs??now;if(!gaps.get(gapKey2)){while(gaps.size>=MAX_LIVENESS_GAPS){let oldest=gaps.keys().next().value;if(oldest===void 0)break;gaps.delete(oldest)}gaps.set(gapKey2,{gapType:"terminal_to_application",openedAtMs:now,eligibleAtMs:Math.max(now,committedAt+config2.gap2StalenessMs)})}}else gaps.delete(gapKey2);break}case"application_marker_committed":{if(input.receiptSource==="architect_marker")gaps.delete(gapKey2);break}case"gate_release_committed":case"phase_closed":case"authorized_transition_committed":{gaps.delete(gapKey1),gaps.delete(gapKey2);break}default:break}evaluateLiveness(input.directory,now)}catch{}}function normalizeParticipationAgent(agent){return(agent.includes("_")?agent.split("_").pop()??agent:agent).trim().toLowerCase()}function observeCuratorCompliance(input){try{ensureLearningHealth();let now=_internals12.now(),scopeKey=`${projectRef(input.directory)}/participation`,scope=ensureScope("role_participation",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.role_participation;for(let type of input.gapTypes){if(!PARTICIPATION_GAP_TYPES.has(type))continue;appendFact(scope,`gap:${type}`,now,config2.windowMs)}for(let agent of input.agentsUsed)appendFact(scope,`participated:${normalizeParticipationAgent(agent)}`,now,config2.windowMs);let gapFacts=scope.facts.filter((f)=>f.kind.startsWith("gap:")),lastGapAtMs=0,openTypes=new Set;for(let fact of scope.facts)if(fact.kind.startsWith("gap:"))lastGapAtMs=Math.max(lastGapAtMs,fact.atMs),openTypes.add(fact.kind.slice(4));let matchingLateParticipation=scope.facts.some((fact)=>{if(!fact.kind.startsWith("participated:"))return!1;if(fact.atMs<lastGapAtMs)return!1;let agent=fact.kind.slice(13);for(let type of openTypes)if(EXPECTED_ROLES_BY_GAP_TYPE[type]?.includes(agent))return!0;return!1});if(gapFacts.length>=config2.raiseFacts&&!matchingLateParticipation)applyAlarmState("role_participation","project",scopeKey,"active",config2.severity,{reason:"eligible_role_gap",phase:input.phase},input.directory,now);else if(matchingLateParticipation)applyAlarmState("role_participation","project",scopeKey,"idle",config2.severity,{},input.directory,now)}catch{}}function observePromotionEvidence(input){try{ensureLearningHealth();let now=_internals12.now(),scopeKey=`${projectRef(input.directory)}/fixture-share`,scope=ensureScope("promoted_fixture_share",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.promoted_fixture_share,source=input.receiptSource??"unknown",isField=FIELD_RECEIPT_SOURCES.has(source);appendFact(scope,isField?"field":"non_field",now,config2.windowMs);let field=countFacts(scope,"field"),nonField=countFacts(scope,"non_field"),total=field+nonField,share=total>0?nonField/total:0,detail={sharePct:Math.round(share*100),fieldCount:field,nonFieldCount:nonField};if(total>=config2.minEvidence&&share>=config2.raiseShare)applyAlarmState("promoted_fixture_share","project",scopeKey,"active",config2.severity,detail,input.directory,now);else if(total>=config2.minEvidence&&share<config2.clearShare)applyAlarmState("promoted_fixture_share","project",scopeKey,"idle",config2.severity,detail,input.directory,now)}catch{}}function observeCloseArchive(input){try{ensureLearningHealth();let now=_internals12.now(),scopeKey=`${projectRef(input.directory)}/archive`,scope=ensureScope("archive_activity_mismatch",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.archive_activity_mismatch,mismatch=(!input.archiveValid||input.archiveEmpty)&&input.activityPredictsContent;appendFact(scope,mismatch?"mismatch":"ok",now,config2.windowMs||1);let detail={reason:mismatch?input.archiveEmpty?"archive_empty_with_activity":"archive_invalid_with_activity":void 0};if(mismatch)applyAlarmState("archive_activity_mismatch","project",scopeKey,"active",config2.severity,detail,input.directory,now);else applyAlarmState("archive_activity_mismatch","project",scopeKey,"idle",config2.severity,{},input.directory,now)}catch{}}function observeDelegationLedgerPressure(input){try{ensureLearningHealth();let now=_internals12.now(),scopeKey=`${projectRef(input.directory)}/ledger`,scope=ensureScope("recovery_ledger_pressure",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.recovery_ledger_pressure,badBand=input.band==="compact-overdue"||input.band==="fail-closed",high=badBand||input.pressurePct>=config2.raisePct,low=!badBand&&input.pressurePct<config2.clearPct&&!input.uncertain;appendFact(scope,high?"high":"ok",now,config2.windowMs);let detail={pressurePct:Math.round(input.pressurePct*100),band:input.band,reason:input.uncertain?"recovery_observation_uncertain":void 0};if(high)applyAlarmState("recovery_ledger_pressure","project",scopeKey,"active",config2.severity,detail,input.directory,now);else if(low)applyAlarmState("recovery_ledger_pressure","project",scopeKey,"idle",config2.severity,detail,input.directory,now)}catch{}}function observeStoreHealth(input){try{observeStoreHealthEvent(input.kind,input.payload,input.directory)}catch{}}function observeStoreHealthEvent(event,data,directory){if(ensureLearningHealth(),!STORE_HEALTH_KINDS.has(event))return;let store=STORE_LABEL_BY_KIND[event];if(!store)return;let corrupt=Math.max(toCount(data.corrupt_count),toCount(data.corrupt)),dropped=Math.max(toCount(data.dropped_count),toCount(data.dropped),toCount(data.dropped_audit_count)),retained=toCount(data.retained_count),accepted=Math.max(toCount(data.accepted_count),toCount(data.accepted)),now=_internals12.now(),scopeKey=directory?`${projectRef(directory)}/store/${store}`:`store/${store}`,scope=ensureScope("compaction_drop_coverage",scopeKey,now),config2=LEARNING_HEALTH_ALARM_CONFIG.compaction_drop_coverage;if(corrupt>0)appendFact(scope,"corrupt",now,config2.windowMs);else if(dropped>=config2.droppedRaise)appendFact(scope,"dropped",now,config2.windowMs);else appendFact(scope,"clean",now,config2.windowMs);let corruptFacts=countFacts(scope,"corrupt"),droppedFacts=countFacts(scope,"dropped"),cleanFacts=countFacts(scope,"clean"),detail={store,dropped,corrupt,retained,accepted};if(corruptFacts>=config2.corruptRaise||droppedFacts>0)applyAlarmState("compaction_drop_coverage","project",scopeKey,"active",droppedFacts>0?"critical":"warning",detail,directory,now);else if(cleanFacts>0&&corruptFacts===0&&droppedFacts===0)applyAlarmState("compaction_drop_coverage","project",scopeKey,"idle","warning",detail,directory,now)}function toCount(value){return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}function ensureLearningHealth(){}async function readLearningHealth(directory){ensureLearningHealth();try{await rehydrateFromArtifact(directory);let now=_internals12.now();evaluateLiveness(directory,now);let scopeOwner=projectRef(directory),active=[];for(let[alarm,scopes]of alarmScopes)for(let[key,scope]of scopes){if(scope.status!=="active")continue;if(!(key.startsWith(`${scopeOwner}/`)||key.startsWith("u/")||key.startsWith("store/")))continue;active.push({alarm,severity:scope.severity,scopeClass:scopeClassFor(alarm),scopeRef:key.split("/").pop()??key,ageMs:scope.raisedAtMs>0?Math.max(0,now-scope.raisedAtMs):0,coverageFacts:scope.factCount,transitionCount:scope.transitionCount})}return schedulePersist(directory,now,!1),{activeAlarms:active,totalTransitions:transitionRing.length,updatedAtMs:now}}catch{return{activeAlarms:[],totalTransitions:0,updatedAtMs:0}}}function scopeClassFor(alarm){switch(alarm){case"headroom_dead_streak":return"session";case"model_limit_fallback":return"identity";default:return"project"}}var HEALTH_SOURCES_TABLE,HEALTH_SOURCES,LEARNING_HEALTH_ALARM_CONFIG,FIELD_RECEIPT_SOURCES,MAX_HEALTH_SCOPES=64,MAX_FACTS_PER_SCOPE=64,MAX_LIVENESS_GAPS=64,MAX_TRANSITION_RING=100,PERSIST_DEBOUNCE_MS=5000,CLOCK_SKEW_TOLERANCE_MS=300000,ARTIFACT_FILENAME="learning-health.json",ARTIFACT_SCHEMA_VERSION=1,STORE_HEALTH_KINDS,STORE_LABEL_BY_KIND,alarmScopes,livenessGaps,transitionRing,lastPersistAtByDirectory,recentPersistDirectories,MAX_TRACKED_DIRECTORIES=16,_internals12,projectRefCache,DETAIL_PAYLOAD_KEYS,PARTICIPATION_GAP_TYPES,EXPECTED_ROLES_BY_GAP_TYPE;var init_learning_health=__esm(()=>{init_ids();init_telemetry();init_atomic_write();HEALTH_SOURCES_TABLE={context_budget:{producer:"src/hooks/context-budget.ts:199",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["headroom_dead_streak"]},model_limits:{producer:"src/hooks/model-limits.ts:333",readers:["src/tools/context-status.ts","src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["model_limit_fallback"]},knowledge_receipts:{producer:"src/hooks/knowledge-receipt-ledger.ts:2219",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["retrieval_outcome_liveness"]},curator_compliance:{producer:"src/hooks/curator.ts:1906",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["role_participation"]},promotion_evidence:{producer:"src/hooks/promotion-evidence-store.ts:94",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["promoted_fixture_share"]},close_archive:{producer:"src/commands/close.ts:754",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["archive_activity_mismatch"]},delegation_ledger:{producer:"src/background/delegation-health.ts:581",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["recovery_ledger_pressure"]},store_health_events:{producer:"src/events/core-events.ts:1616 (direct observeStoreHealth; one per audited store)",readers:["src/services/status-service.ts","src/services/diagnose-service.ts"],alarms:["compaction_drop_coverage"]}},HEALTH_SOURCES=Object.freeze(HEALTH_SOURCES_TABLE),LEARNING_HEALTH_ALARM_CONFIG=Object.freeze({headroom_dead_streak:Object.freeze({windowMs:600000,raiseFacts:3,cooldownMs:1800000,severity:"warning"}),model_limit_fallback:Object.freeze({windowMs:1800000,cooldownMs:3600000,severity:"warning"}),retrieval_outcome_liveness:Object.freeze({windowMs:1800000,cooldownMs:900000,severity:"warning",gap2StalenessMs:600000}),role_participation:Object.freeze({windowMs:86400000,raiseFacts:2,cooldownMs:43200000,severity:"warning"}),promoted_fixture_share:Object.freeze({windowMs:604800000,raiseShare:0.5,clearShare:0.3,minEvidence:4,cooldownMs:86400000,severity:"warning"}),archive_activity_mismatch:Object.freeze({windowMs:0,cooldownMs:86400000,severity:"warning"}),recovery_ledger_pressure:Object.freeze({windowMs:900000,raisePct:0.8,clearPct:0.7,cooldownMs:1800000,severity:"warning"}),compaction_drop_coverage:Object.freeze({windowMs:3600000,corruptRaise:1,droppedRaise:100,cooldownMs:3600000,severity:"warning"})}),FIELD_RECEIPT_SOURCES=new Set(["delegate","reviewer","architect","architect_marker","test_engineer"]),STORE_HEALTH_KINDS=new Set(["context_telemetry_health","skill_usage_health","core_events_health","shell_audit_health","trajectory_health","pr_subscription_health"]),STORE_LABEL_BY_KIND=Object.freeze({context_telemetry_health:"context_telemetry",skill_usage_health:"skill_usage",core_events_health:"core_events",shell_audit_health:"shell_audit",trajectory_health:"trajectory",pr_subscription_health:"pr_subscription"}),alarmScopes=new Map,livenessGaps=new Map,transitionRing=[],lastPersistAtByDirectory=new Map,recentPersistDirectories=[];_internals12={now:()=>Date.now(),emitTelemetry:(payload)=>{telemetry.learningHealthAlarm(payload)},writeArtifact:(directory,contents)=>atomicWriteSwarmFile(path14.join(directory,".swarm",ARTIFACT_FILENAME),contents),readArtifact:async(directory)=>{try{return await fs9.readFile(path14.join(directory,".swarm",ARTIFACT_FILENAME),"utf-8")}catch{return null}}},projectRefCache=new Map;DETAIL_PAYLOAD_KEYS=Object.freeze({sessionRef:"session_ref",limitSource:"limit_source",denominatorFallback:"denominator_fallback",pressurePct:"pressure_pct",sharePct:"share_pct",fieldCount:"field_count",nonFieldCount:"non_field_count",gapType:"gap_type"});PARTICIPATION_GAP_TYPES=new Set(["missing_reviewer","missing_retro","missing_sme"]),EXPECTED_ROLES_BY_GAP_TYPE=Object.freeze({missing_reviewer:Object.freeze(["reviewer"]),missing_sme:Object.freeze(["sme"]),missing_retro:Object.freeze(["reviewer","architect"])})});import*as fs10 from"node:fs";import*as path15 from"node:path";function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function healthArtifactPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_HEALTH_FILE)}function readDelegationHealthArtifact(directory){let raw;try{raw=fs10.readFileSync(healthArtifactPath(directory),"utf-8")}catch{return null}try{let parsed=DelegationLedgerHealthSchema.safeParse(JSON.parse(raw));return parsed.success?parsed.data:null}catch{return null}}function writeDelegationHealthArtifact(directory,update){let base=readDelegationHealthArtifact(directory)??{schemaVersion:1,updatedAt:0,ledger:{bytes:0,limitBytes:MAX_RECOVERY_LEDGER_BYTES,pressurePct:0,band:"ok"},checkpoint:null,recovery:null,lastUncertainty:null,counts:{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:null},next={schemaVersion:1,updatedAt:Date.now(),ledger:update.ledger??base.ledger,checkpoint:update.checkpoint===void 0?base.checkpoint:update.checkpoint,recovery:update.recovery===void 0?base.recovery:update.recovery,lastUncertainty:update.lastUncertainty??base.lastUncertainty,counts:update.counts??base.counts,maintenance:update.maintenance===void 0?base.maintenance??null:update.maintenance};if(update.uncertainty)next.lastUncertainty=update.uncertainty;let parsed=DelegationLedgerHealthSchema.safeParse(next);if(!parsed.success)return null;try{fs10.mkdirSync(path15.resolve(directory,".swarm"),{recursive:!0});let target=healthArtifactPath(directory),tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;fs10.writeFileSync(tmp,`${JSON.stringify(parsed.data)}
|
|
190
190
|
`,"utf-8");let lastError;for(let attempt=0;attempt<5;attempt++)try{_healthInternals.renameOnce(tmp,target),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<4)sleepSync(15)}if(lastError!==void 0){try{fs10.rmSync(tmp,{force:!0})}catch{}return null}return parsed.data}catch{return null}}function recordDelegationRecoveryObservation(directory,observation){try{writeDelegationHealthArtifact(directory,{recovery:{source:observation.source,at:Date.now(),ok:observation.ok,...observation.reason?{reason:observation.reason}:{},...observation.repairHint?{repairHint:observation.repairHint}:{}},...observation.ok?{}:{uncertainty:{reason:observation.reason??"recovery failed",at:Date.now(),source:"recovery",...observation.repairHint?{repairHint:observation.repairHint}:{}}}})}catch{}}function appendDelegationMaintenanceObservation(directory,observation){try{let current=readDelegationHealthArtifact(directory)?.maintenance??null,section={lastRunAt:observation.at,lastOkAt:observation.status==="ok"?observation.at:current?.lastOkAt??null,lastFailure:observation.status==="failure"&&observation.reason?{reason:observation.reason,at:observation.at}:current?.lastFailure??null,lastContentionAt:observation.status==="contention"?observation.at:current?.lastContentionAt??null,lastSummary:observation.summary??current?.lastSummary??{sweptStale:0,released:0,renewed:0,retained:0},facts:[...current?.facts??[],...observation.facts].slice(-MAX_MAINTENANCE_FACTS)};writeDelegationHealthArtifact(directory,{maintenance:section})}catch{}}function collectDelegationLedgerHealth(directory,options){let artifact=readDelegationHealthArtifact(directory),ledgerBytes=0,ledgerExists=!1;try{ledgerBytes=fs10.statSync(validateSwarmPath(directory,"background-delegations.jsonl")).size,ledgerExists=!0}catch{ledgerExists=!1}if(!artifact&&!ledgerExists)return null;let limitBytes=options.ledgerLimitBytes,pressurePct=Math.min(100,Math.round(ledgerBytes/limitBytes*1000)/10),band=ledgerBytes>limitBytes?"fail-closed":ledgerBytes>options.highWaterBytes?"compact-overdue":ledgerBytes>options.lowWaterBytes?"nominal":"ok";return observeDelegationLedgerPressure({directory,pressurePct:pressurePct/100,band,uncertain:artifact?.lastUncertainty!=null}),{schemaVersion:1,updatedAt:artifact?.updatedAt??0,ledger:{bytes:ledgerBytes,limitBytes,pressurePct,band},checkpoint:artifact?.checkpoint??null,recovery:artifact?.recovery??null,lastUncertainty:artifact?.lastUncertainty??null,counts:artifact?.counts??{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:artifact?.maintenance??null}}var BACKGROUND_DELEGATIONS_HEALTH_FILE="background-delegations-health.json",MAX_RECOVERY_LEDGER_BYTES=4194304,DelegationCheckpointAuditSchema,CheckpointSectionSchema,RecoverySectionSchema,UncertaintySectionSchema,MAX_MAINTENANCE_FACTS=20,DelegationMaintenanceFactSchema,MaintenanceSectionSchema,DelegationLedgerHealthSchema,_healthInternals;var init_delegation_health=__esm(()=>{init_zod();init_learning_health();init_utils2();DelegationCheckpointAuditSchema=exports_external.object({dispatchCount:exports_external.number().int().nonnegative(),terminalsByStatus:exports_external.object({completed:exports_external.number().int().nonnegative(),error:exports_external.number().int().nonnegative(),cancelled:exports_external.number().int().nonnegative(),stale:exports_external.number().int().nonnegative()}).strict(),settledCount:exports_external.number().int().nonnegative(),preservedCount:exports_external.number().int().nonnegative(),lateTerminalCount:exports_external.number().int().nonnegative(),compactedTransitionCount:exports_external.number().int().nonnegative(),compactedRecordCount:exports_external.number().int().nonnegative(),firstDispatchAt:exports_external.number().int().nonnegative().nullable(),lastTerminalAt:exports_external.number().int().nonnegative().nullable(),lastCompactionAt:exports_external.number().int().nonnegative()}).strict(),CheckpointSectionSchema=exports_external.object({sequence:exports_external.number().int().positive(),createdAt:exports_external.number().int().nonnegative(),liveRecords:exports_external.number().int().nonnegative(),closedSummaries:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),audit:DelegationCheckpointAuditSchema}).strict(),RecoverySectionSchema=exports_external.object({source:exports_external.enum(["checkpoint+tail","checkpoint+ledger-suffix","legacy-ledger","unknown"]),at:exports_external.number().int().nonnegative(),ok:exports_external.boolean(),reason:exports_external.string().min(1).max(2000).optional(),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),UncertaintySectionSchema=exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative(),source:exports_external.string().min(1).max(256),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),DelegationMaintenanceFactSchema=exports_external.object({at:exports_external.number().int().nonnegative(),kind:exports_external.enum(["release","retained-ambiguity","retained-protected-legacy","lease-renewed","maintenance-failure","lock-contention"]),reservationId:exports_external.string().min(1).max(256).optional(),correlationId:exports_external.string().min(1).max(256).optional(),generation:exports_external.number().int().positive().optional(),reason:exports_external.string().min(1).max(2000)}).strict(),MaintenanceSectionSchema=exports_external.object({lastRunAt:exports_external.number().int().nonnegative(),lastOkAt:exports_external.number().int().nonnegative().nullable(),lastFailure:exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative()}).strict().nullable(),lastContentionAt:exports_external.number().int().nonnegative().nullable(),lastSummary:exports_external.object({sweptStale:exports_external.number().int().nonnegative(),released:exports_external.number().int().nonnegative(),renewed:exports_external.number().int().nonnegative(),retained:exports_external.number().int().nonnegative()}).strict(),facts:exports_external.array(DelegationMaintenanceFactSchema).max(MAX_MAINTENANCE_FACTS)}).strict(),DelegationLedgerHealthSchema=exports_external.object({schemaVersion:exports_external.literal(1),updatedAt:exports_external.number().int().nonnegative(),ledger:exports_external.object({bytes:exports_external.number().int().nonnegative(),limitBytes:exports_external.number().int().positive(),pressurePct:exports_external.number().min(0).max(100),band:exports_external.enum(["ok","nominal","compact-overdue","fail-closed"])}).strict(),checkpoint:CheckpointSectionSchema.nullable(),recovery:RecoverySectionSchema.nullable(),lastUncertainty:UncertaintySectionSchema.nullable(),counts:exports_external.object({activeOwners:exports_external.number().int().nonnegative(),pendingAdvisories:exports_external.number().int().nonnegative(),lateTerminals:exports_external.number().int().nonnegative(),orphanWorktreeOwners:exports_external.number().int().nonnegative()}).strict(),maintenance:MaintenanceSectionSchema.nullable().optional()}).strict();_healthInternals={renameOnce:(from,to)=>{fs10.renameSync(from,to)}}});import{createHash as createHash6}from"node:crypto";function resolveLaneAtomicDisposition(receipt){if(new Set(receipt.assignedReviewItemIds).size!==receipt.assignedReviewItemIds.length)return null;let acceptedAll=receipt.rejectedReviewItemIds.length===0&&receipt.acceptedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.acceptedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]),rejectedAll=receipt.acceptedReviewItemIds.length===0&&receipt.rejectedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.rejectedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]);return acceptedAll?"accepted":rejectedAll?"rejected":null}function encodePrReviewCollectionReceiptFooter(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);if(!payload)return null;let footer=`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(payload)}`;return footer.length<=MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS?footer:null}function buildPrReviewCollectionReceiptPayload(binding,result,receipt){let disposition=resolveLaneAtomicDisposition(receipt);if(!disposition)return null;let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse({schemaVersion:1,parentSessionId:binding.parentSessionId,batchId:binding.batchId??binding.callID,laneId:binding.laneId??binding.correlationId,mode:binding.mode,workflowLane:binding.workflowLane,outputDigest:result.digest,disposition,reviewItemIds:receipt.assignedReviewItemIds});if(!parsed.success)return null;return parsed.data}function projectPrReviewCollectionReceipt(payload){let assignedReviewItemIds=[...payload.reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:payload.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:payload.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function reviewItemDigest(reviewItemIds){return createHash6("sha256").update(JSON.stringify(reviewItemIds)).digest("hex")}function encodePrReviewCollectionReceiptShedMarker(payload){let marker={schemaVersion:1,parentSessionId:payload.parentSessionId,batchId:payload.batchId,laneId:payload.laneId,mode:payload.mode,workflowLane:payload.workflowLane,outputDigest:payload.outputDigest,disposition:payload.disposition,reviewItemCount:payload.reviewItemIds.length,reviewItemDigest:reviewItemDigest(payload.reviewItemIds)};return`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker)}`}function encodePrReviewCollectionReceiptShedMarkerFromReceipt(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);return payload?encodePrReviewCollectionReceiptShedMarker(payload):null}function parsePrReviewCollectionReceiptShedMarker(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),markerLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)),finalLine=lines.at(-1);if(markerLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptShedMarkerSchema.safeParse(decoded);if(!parsed.success)return null;let marker=parsed.data;return marker.parentSessionId===binding.parentSessionId&&marker.batchId===(binding.batchId??binding.callID)&&marker.laneId===(binding.laneId??binding.correlationId)&&marker.mode===binding.mode&&marker.workflowLane===binding.workflowLane&&marker.outputDigest===result.digest?marker:null}function projectPrReviewCollectionReceiptShedMarker(marker,reviewItemIds){if(marker.reviewItemCount!==reviewItemIds.length||marker.reviewItemDigest!==reviewItemDigest(reviewItemIds))return null;let assignedReviewItemIds=[...reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:marker.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:marker.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function parsePrReviewCollectionReceiptFooter(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),receiptLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)),finalLine=lines.at(-1);if(receiptLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse(decoded);if(!parsed.success)return null;let payload=parsed.data;return payload.parentSessionId===binding.parentSessionId&&payload.batchId===(binding.batchId??binding.callID)&&payload.laneId===(binding.laneId??binding.correlationId)&&payload.mode===binding.mode&&payload.workflowLane===binding.workflowLane&&payload.outputDigest===result.digest?payload:null}var PR_REVIEW_COLLECTION_RECEIPT_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_V1] ",PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_SHED_V1] ",MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS=65536,MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS=1e4,PrReviewCollectionReceiptPayloadSchema,PrReviewCollectionReceiptShedMarkerSchema;var init_pr_review_collection_receipt=__esm(()=>{init_zod();PrReviewCollectionReceiptPayloadSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemIds:exports_external.array(exports_external.string().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)}).strict().superRefine((payload,context)=>{if(new Set(payload.reviewItemIds).size!==payload.reviewItemIds.length)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"review item IDs must be unique"})}),PrReviewCollectionReceiptShedMarkerSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemCount:exports_external.number().int().positive().max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS),reviewItemDigest:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteUrlIdentityAsync:()=>resolveRemoteUrlIdentityAsync,resolveRemoteUrlIdentity:()=>resolveRemoteUrlIdentity,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentLocalHeadRefAsync:()=>resolveCurrentLocalHeadRefAsync,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,redactRemoteUrlIdentity:()=>redactRemoteUrlIdentity,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,isSwarmRuntimePath:()=>isSwarmRuntimePath,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals13});import*as child_process from"node:child_process";import{createHash as createHash7}from"node:crypto";import*as fs11 from"node:fs";import*as path16 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals13.spawnSync(_internals13.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals13.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals13.bunSpawn([_internals13.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve10)=>{timeout=setTimeout(()=>resolve10({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals13.spawnSync(_internals13.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals13.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals13.bunSpawn([_internals13.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals13.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve10)=>{timeout=setTimeout(()=>resolve10({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals13.spawnSync(_internals13.resolveGitExecutable(),["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
|
|
191
191
|
`)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=runGit(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
|
|
@@ -215,15 +215,15 @@ ${lines[i]}`),framingChecked=!0}else{let prefix=!framingChecked&&!fileEndsWithNe
|
|
|
215
215
|
`),emitHealth(directory,{trigger,accepted:folded.totalEvents+finalRetained.length,compacted:toFold.size-dropped,retained:finalRetained.length,dropped,corrupt:folded.corrupt,oldest:folded.oldestTimestamp,newest:folded.newestTimestamp,bytes:fileSizeOrZero(filePath),limitBytes:_internals14.limits.activeMaxBytes},preloadedAuthorityState)}function runMaintenance(directory){try{let filePath=eventsFilePath(directory);if(!_internals14.existsSync(filePath))return;let drainThreshold=_internals14.limits.activeMaxBytes+_internals14.limits.headerMaxBytes+2048;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory);foldPass(directory,"compaction",!1,authorityState);let prevSize=Number.POSITIVE_INFINITY;for(let pass=0;pass<64;pass+=1){let size=fileSizeOrZero(filePath);if(size<=drainThreshold)break;if(size>=prevSize)break;prevSize=size,foldPass(directory,"compaction",!1,authorityState)}return!0})}catch{warnThrottled("maintenance pass failed")}}function finalizeCoreEventsForClose(directory){try{let filePath=eventsFilePath(directory);if(!_internals14.existsSync(filePath))return;withCoreEventStoreLock(directory,()=>{let authorityState=loadAuthorityIndex(directory),prev=Number.POSITIVE_INFINITY;for(let pass=0;pass<1e4;pass+=1){let view=readStoreFull(directory);if(view.manifest!==null)break;if(view.lines.length===0)break;if(view.lines.length>=prev)break;prev=view.lines.length,foldPass(directory,"close",!1,authorityState)}return foldPass(directory,"close",!0,authorityState),!0})}catch{warnThrottled("finalize failed")}}function emitCoreEventsHealth(directory,payload,preloadedAuthorityState){let authorityCount=0,authorityEvicted=0,state=preloadedAuthorityState??loadAuthorityIndex(directory);if(state.kind==="ok")authorityCount=Object.keys(state.index.entries).length,authorityEvicted=state.index.evicted;let healthPayload={trigger:payload.trigger,accepted_count:payload.accepted,compacted_count:payload.compacted,retained_count:payload.retained,dropped_count:payload.dropped,corrupt_count:payload.corrupt,authority_index_count:authorityCount,authority_evicted_count:authorityEvicted,oldest_timestamp:payload.oldest,newest_timestamp:payload.newest,bytes:payload.bytes,limit_bytes:payload.limitBytes};try{telemetry.coreEventsHealth(healthPayload),observeStoreHealth({directory,kind:"core_events_health",payload:healthPayload})}catch{}}function emitHealth(directory,payload,preloadedAuthorityState){_internals14.emitHealth(directory,payload,preloadedAuthorityState)}var CORE_EVENT_LIMITS,AUTHORITY_RETRY="coder_retry_circuit_breaker",AUTHORITY_REPAIR="task_workflow_repaired",AUTHORITY_DRIFT_ACK="spec_drift_acknowledged",AUTHORITY_DRIFT_REPAIR="spec_drift_repaired",PUBLICATION_LIVE_EVENT_TYPES,PUBLICATION_TERMINAL_EVENT_TYPES,RETRY_ACTIONS,MANIFEST_TYPE="swarm-events-manifest",MANIFEST_SCHEMA=1,BY_TYPE_MAX_KEYS=64,BY_TYPE_OTHER="__other__",_internals14,LOCK_RETRY_ATTEMPTS=20,LOCK_RETRY_DELAY_MS=5,LOCK_STALE_MS=300000,sleepScratch,RENAME_RETRY_DELAYS_MS2,RETRYABLE_RENAME_CODES2,_appendCount=0,_lastWarnAt=0,CORE_EVENT_LOCKED="CORE_EVENT_STORE_LOCKED",CORE_EVENT_LINE_TOO_LARGE="CORE_EVENT_LINE_TOO_LARGE",CORE_EVENT_NO_STORE="CORE_EVENT_NO_STORE";var init_core_events=__esm(()=>{init_learning_health();init_telemetry();init_logger();CORE_EVENT_LIMITS={activeMaxBytes:2097152,activeMaxEntries:20000,ageMaxMs:604800000,compactMaxBytes:524288,readMaxBytes:3145728,checkInterval:25,warnCooldownMs:60000,headerMaxBytes:65536,authorityIndexMaxEntries:20000,maxLineBytes:262144},PUBLICATION_LIVE_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started"]),PUBLICATION_TERMINAL_EVENT_TYPES=new Set(["pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]),RETRY_ACTIONS=new Set(["sounding_board_consultation","simplification","user_escalation"]);_internals14={appendFileSync:fs12.appendFileSync,readFileSync:fs12.readFileSync,existsSync:fs12.existsSync,mkdirSync:fs12.mkdirSync,statSync:fs12.statSync,renameSync:fs12.renameSync,writeFileSync:fs12.writeFileSync,unlinkSync:fs12.unlinkSync,openSync:fs12.openSync,closeSync:fs12.closeSync,readSync:fs12.readSync,now:()=>Date.now(),limits:CORE_EVENT_LIMITS,emitHealth:emitCoreEventsHealth};sleepScratch=new Int32Array(new SharedArrayBuffer(4));RENAME_RETRY_DELAYS_MS2=[10,25,50,100,200],RETRYABLE_RENAME_CODES2=new Set(["EPERM","EBUSY","EACCES","EEXIST"])});import*as path18 from"node:path";function taskEvidenceRelPath(taskId){return path18.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path18.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash8}from"node:crypto";import*as fs13 from"node:fs";import*as path19 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path19.resolve(value).toLowerCase():path19.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs13.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs13.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path19.join(current,segment);let info;try{info=fs13.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs13.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs13.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs13.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path19.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash8("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs13.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs13.openSync(filePath,fs13.constants.O_RDONLY|(fs13.constants.O_NOFOLLOW??0));try{let openedStat=fs13.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs13.readFileSync(descriptor,"utf-8")}finally{fs13.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
216
216
|
`)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event);if(!role||!shouldAppendReceipt(current,next,role))return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId)return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
|
|
217
217
|
`)}
|
|
218
|
-
`),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path20 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path20){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path20.win32:path20.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs14 from"node:fs";import*as path21 from"node:path";function recoveryDir(directory){return path21.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path21.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs14.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs14.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path21.join(dir,entry.name);try{let parsed=JSON.parse(fs14.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs14.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs14.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs14.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs14.existsSync(filePath))fs14.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import{createHash as createHash9}from"node:crypto";function derivePlanId(plan){return`${plan.swarm}-${plan.title}`.replace(/[^a-zA-Z0-9-_]/g,"_")}function derivePlanIdentityHash(plan){return createHash9("sha256").update(JSON.stringify([plan.swarm,plan.title]),"utf8").digest("hex")}var init_utils3=()=>{};import*as crypto3 from"node:crypto";import*as fs15 from"node:fs";import*as path22 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path22.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path22.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs15.openSync(tempPath,"w");try{fs15.writeFileSync(fd,data,"utf8"),fs15.fsyncSync(fd)}finally{fs15.closeSync(fd)}fs15.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs15.openSync(directory,"r"),fs15.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs15.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs15.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs15.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return 0;try{let lines=fs15.readFileSync(ledgerPath,"utf8").trim().split(`
|
|
218
|
+
`),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path20 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path20){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path20.win32:path20.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs14 from"node:fs";import*as path21 from"node:path";function recoveryDir(directory){return path21.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path21.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs14.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs14.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path21.join(dir,entry.name);try{let parsed=JSON.parse(fs14.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs14.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs14.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs14.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs14.existsSync(filePath))fs14.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import{createHash as createHash9}from"node:crypto";function derivePlanId(plan){return`${plan.swarm}-${plan.title}`.replace(/[^a-zA-Z0-9-_]/g,"_")}function derivePlanIdentityHash(plan){return createHash9("sha256").update(JSON.stringify([plan.swarm,plan.title]),"utf8").digest("hex")}var init_utils3=()=>{};import*as crypto3 from"node:crypto";import*as fs15 from"node:fs";import*as path22 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanLedgerHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path22.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path22.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanLedgerHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs15.openSync(tempPath,"w");try{fs15.writeFileSync(fd,data,"utf8"),fs15.fsyncSync(fd)}finally{fs15.closeSync(fd)}fs15.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs15.openSync(directory,"r"),fs15.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs15.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanLedgerHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs15.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanLedgerHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs15.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return 0;try{let lines=fs15.readFileSync(ledgerPath,"utf8").trim().split(`
|
|
219
219
|
`).filter((line)=>line.trim()!=="");if(lines.length===0)return 0;let maxSeq=0;for(let line of lines)try{let event=JSON.parse(line);if(event.seq>maxSeq)maxSeq=event.seq}catch{}return maxSeq}catch{return 0}}async function readLedgerEvents(directory){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return[];try{let lines=fs15.readFileSync(ledgerPath,"utf8").trim().split(`
|
|
220
|
-
`).filter((line)=>line.trim()!==""),events=[],skippedCount=0;for(let line of lines)try{let event=JSON.parse(line);events.push(event)}catch{skippedCount++}if(skippedCount>0)log(`[ledger] Skipped ${skippedCount} malformed line(s) in plan-ledger.jsonl`);return events.sort((a,b)=>a.seq-b.seq),events}catch{return[]}}async function initLedger(directory,planId,initialPlanHash,initialPlan){assertProjectRoot(directory);let ledgerPath=getLedgerPath(directory),planJsonPath=getPlanJsonPath(directory);if(fs15.existsSync(ledgerPath))throw Error("Ledger already initialized. Use appendLedgerEvent to add events.");let planHashAfter=initialPlanHash??"",embeddedPlan=initialPlan;if(!initialPlanHash)try{if(fs15.existsSync(planJsonPath)){let content=fs15.readFileSync(planJsonPath,"utf8"),plan=JSON.parse(content);if(planHashAfter=
|
|
221
|
-
`;writeFileFsyncedThenRename(tempPath,ledgerPath,line)}async function readLedgerEventsForEpoch(directory){let integrity=await _internals15.readLedgerEventsWithIntegrity(directory,{failClosedOnReadError:!0});if(integrity.truncated)throw Error(`PLAN_LEDGER_TRUNCATED: ${getLedgerPath(directory)} has a malformed line; plan epoch identity cannot be resolved. Preserve this file and quarantine the corrupted suffix before retrying.`);return integrity.events}async function readPlanEpochIdentity(directory,authoritativePlan){if(assertProjectRoot(directory),!await ledgerExists(directory))return null;let events=await readLedgerEventsForEpoch(directory);if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");return resolvePlanEpochIdentity(events,authoritativePlan)}async function getOrAdoptPlanEpochUnderLock(directory,authoritativePlan){assertProjectRoot(directory);let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=
|
|
222
|
-
`;if(!fs15.existsSync(ledgerPath))throw Error("Ledger not initialized. Call initLedger() first.");let existingContent=fs15.readFileSync(ledgerPath,"utf8");return writeFileFsyncedThenRename(tempPath,ledgerPath,existingContent+line),event})}async function appendLedgerEventWithRetry(directory,eventInput,options){let maxRetries=options.maxRetries??3,backoffBase=options.backoffMs??10,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let delayMs=backoffBase*2**(attempt-1);if(await new Promise((resolve11)=>setTimeout(resolve11,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function takeSnapshotWithRetry(directory,plan,options){let telemetrySource=options?.source??"save_plan_tool",snapshotOptions={planHashAfter:options?.planHashAfter},lastError;for(let attempt=1;attempt<=4;attempt++)try{await takeSnapshotEvent(directory,plan,snapshotOptions);return}catch(err){if(lastError=err instanceof Error?err:Error(String(err)),attempt<4)await new Promise((r)=>setTimeout(r,10*2**(attempt-1)))}criticalWarn(`[takeSnapshotWithRetry] Snapshot failed after 3 retries (4 attempts): ${lastError.message}`);try{emit("snapshot_failed",{error:lastError.message,retries:3,source:telemetrySource})}catch{}}async function takeSnapshotEvent(directory,plan,options){let payloadHash=options?.payloadHashOverride??
|
|
220
|
+
`).filter((line)=>line.trim()!==""),events=[],skippedCount=0;for(let line of lines)try{let event=JSON.parse(line);events.push(event)}catch{skippedCount++}if(skippedCount>0)log(`[ledger] Skipped ${skippedCount} malformed line(s) in plan-ledger.jsonl`);return events.sort((a,b)=>a.seq-b.seq),events}catch{return[]}}async function initLedger(directory,planId,initialPlanHash,initialPlan){assertProjectRoot(directory);let ledgerPath=getLedgerPath(directory),planJsonPath=getPlanJsonPath(directory);if(fs15.existsSync(ledgerPath))throw Error("Ledger already initialized. Use appendLedgerEvent to add events.");let planHashAfter=initialPlanHash??"",embeddedPlan=initialPlan;if(!initialPlanHash)try{if(fs15.existsSync(planJsonPath)){let content=fs15.readFileSync(planJsonPath,"utf8"),plan=JSON.parse(content);if(planHashAfter=computePlanLedgerHash(plan),!embeddedPlan)embeddedPlan=plan}}catch{}let payload={plan_epoch:crypto3.randomUUID(),...embeddedPlan?{plan:embeddedPlan,payload_hash:planHashAfter}:{}},event={seq:1,timestamp:new Date().toISOString(),plan_id:planId,event_type:"plan_created",source:"initLedger",plan_hash_before:"",plan_hash_after:planHashAfter,schema_version:LEDGER_SCHEMA_VERSION,...payload?{payload}:{}};fs15.mkdirSync(path22.join(directory,".swarm"),{recursive:!0});let tempPath=`${ledgerPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`,line=`${JSON.stringify(event)}
|
|
221
|
+
`;writeFileFsyncedThenRename(tempPath,ledgerPath,line)}async function readLedgerEventsForEpoch(directory){let integrity=await _internals15.readLedgerEventsWithIntegrity(directory,{failClosedOnReadError:!0});if(integrity.truncated)throw Error(`PLAN_LEDGER_TRUNCATED: ${getLedgerPath(directory)} has a malformed line; plan epoch identity cannot be resolved. Preserve this file and quarantine the corrupted suffix before retrying.`);return integrity.events}async function readPlanEpochIdentity(directory,authoritativePlan){if(assertProjectRoot(directory),!await ledgerExists(directory))return null;let events=await readLedgerEventsForEpoch(directory);if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");return resolvePlanEpochIdentity(events,authoritativePlan)}async function getOrAdoptPlanEpochUnderLock(directory,authoritativePlan){assertProjectRoot(directory);let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanLedgerHash(authoritativePlan),lastStaleWriterError;for(let attempt=0;attempt<4;attempt++){if(!await ledgerExists(directory))try{await initLedger(directory,planId,payloadHash,authoritativePlan)}catch(error49){if(!(error49 instanceof Error&&error49.message.includes("Ledger already initialized")))throw error49}let events=await readLedgerEventsForEpoch(directory),existing=resolvePlanEpochIdentity(events,authoritativePlan);if(existing)return existing;if(events.length===0)throw Error("Plan ledger is empty; cannot adopt a plan epoch.");let rootEvent=events[0],rootEventHash=computeLedgerEventHash(rootEvent),tail=events[events.length-1],planEpoch=_internals15.randomUUID(),adoptionPayload={plan:authoritativePlan,payload_hash:payloadHash,plan_epoch:planEpoch,root_event_hash:rootEventHash};try{let appended=await _internals15.appendLedgerEvent(directory,{event_type:"snapshot",source:"plan_epoch_adopted",plan_id:planId,payload:adoptionPayload},{expectedSeq:tail.seq,expectedLedgerHash:tail.plan_hash_after,planHashAfter:payloadHash}),verifiedEvents=await readLedgerEventsForEpoch(directory),verified=verifiedEvents[verifiedEvents.length-1],verifiedPayload=asRecord(verified?.payload);if(!verified||verified.seq!==appended.seq||verified.event_type!=="snapshot"||verified.source!=="plan_epoch_adopted"||verified.plan_id!==planId||verifiedPayload?.plan_epoch!==planEpoch||verifiedPayload?.root_event_hash!==rootEventHash||verifiedPayload?.payload_hash!==payloadHash)throw Error(`Plan epoch adoption read verification failed for ${planId}.`);return{planId,planIdentityHash,planEpoch,rootEventHash,payloadHash,source:"plan_epoch_adopted"}}catch(error49){if(error49 instanceof LedgerStaleWriterError){lastStaleWriterError=error49;continue}throw error49}}throw Error(`Unable to settle plan epoch for ${planId} after repeated stale-writer retries.`,{cause:lastStaleWriterError})}async function appendLedgerEvent(directory,eventInput,options){return assertProjectRoot(directory),withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","append-ledger-event",async()=>{let ledgerPath=getLedgerPath(directory);if(options?.expectedLedgerHash!==void 0&&options.expectedSeq===void 0)throw Error("expectedLedgerHash requires expectedSeq so stale-projection recovery is bound to one exact ledger tail");let latestSeq=await getLatestLedgerSeq(directory),nextSeq=latestSeq+1,ledgerHashBefore;if(options?.expectedLedgerHash!==void 0){let events=await readLedgerEvents(directory),tail=events[events.length-1];if(!tail||tail.plan_hash_after!==options.expectedLedgerHash)throw new LedgerStaleWriterError(`Stale writer: expected ledger hash ${options.expectedLedgerHash} but found ${tail?.plan_hash_after??"<missing>"}`);ledgerHashBefore=tail.plan_hash_after}let planHashBefore=computeCurrentPlanHash(directory);if(options?.expectedSeq!==void 0&&options.expectedSeq!==latestSeq)throw new LedgerStaleWriterError(`Stale writer: expected seq ${options.expectedSeq} but found ${latestSeq}`);if(options?.expectedHash!==void 0&&options.expectedHash!==planHashBefore)throw new LedgerStaleWriterError(`Stale writer: expected hash ${options.expectedHash} but found ${planHashBefore}`);let planHashAfter=options?.planHashAfter??planHashBefore,event={...eventInput,seq:nextSeq,timestamp:new Date().toISOString(),plan_hash_before:ledgerHashBefore??planHashBefore,plan_hash_after:planHashAfter,schema_version:LEDGER_SCHEMA_VERSION};fs15.mkdirSync(path22.join(directory,".swarm"),{recursive:!0});let tempPath=`${ledgerPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`,line=`${JSON.stringify(event)}
|
|
222
|
+
`;if(!fs15.existsSync(ledgerPath))throw Error("Ledger not initialized. Call initLedger() first.");let existingContent=fs15.readFileSync(ledgerPath,"utf8");return writeFileFsyncedThenRename(tempPath,ledgerPath,existingContent+line),event})}async function appendLedgerEventWithRetry(directory,eventInput,options){let maxRetries=options.maxRetries??3,backoffBase=options.backoffMs??10,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let delayMs=backoffBase*2**(attempt-1);if(await new Promise((resolve11)=>setTimeout(resolve11,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function takeSnapshotWithRetry(directory,plan,options){let telemetrySource=options?.source??"save_plan_tool",snapshotOptions={planHashAfter:options?.planHashAfter},lastError;for(let attempt=1;attempt<=4;attempt++)try{await takeSnapshotEvent(directory,plan,snapshotOptions);return}catch(err){if(lastError=err instanceof Error?err:Error(String(err)),attempt<4)await new Promise((r)=>setTimeout(r,10*2**(attempt-1)))}criticalWarn(`[takeSnapshotWithRetry] Snapshot failed after 3 retries (4 attempts): ${lastError.message}`);try{emit("snapshot_failed",{error:lastError.message,retries:3,source:telemetrySource})}catch{}}async function takeSnapshotEvent(directory,plan,options){let payloadHash=options?.payloadHashOverride??(options?.source==="critic_approved"?computePlanStructureHash(plan):computePlanLedgerHash(plan)),snapshotPayload={plan,payload_hash:payloadHash};if(options?.approvalMetadata)snapshotPayload.approval=options.approvalMetadata;let planId=derivePlanId(plan);return appendLedgerEvent(directory,{event_type:"snapshot",source:options?.source??"takeSnapshotEvent",plan_id:planId,payload:snapshotPayload},{planHashAfter:options?.planHashAfter,expectedSeq:options?.expectedSeq,expectedLedgerHash:options?.expectedLedgerHash})}async function replaceTruncatedLedgerWithRecoveryRoot(directory,plan,expected){assertProjectRoot(directory);let validated=PlanSchema.parse(plan);return withEvidenceLock(directory,LEDGER_LOCK_PATH,"plan-ledger","reconcile-truncated-ledger",async()=>{let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))throw new LedgerStaleWriterError("Stale writer: canonical ledger disappeared before truncated-ledger recovery");let events=await readLedgerEvents(directory),tail=events[events.length-1];if(!tail||tail.seq!==expected.seq||tail.plan_hash_after!==expected.ledgerHash||events[0]?.plan_id!==derivePlanId(validated))throw new LedgerStaleWriterError("Stale writer: ledger identity or tail changed before truncated-ledger recovery");let integrity=await readLedgerEventsWithIntegrity(directory);if(!integrity.truncated||integrity.badSuffix===null)throw new LedgerStaleWriterError("Stale writer: ledger is no longer truncated; retry against its current tail");let originalBytes=fs15.readFileSync(ledgerPath),archiveSha256=crypto3.createHash("sha256").update(originalBytes).digest("hex"),swarmDir=path22.dirname(ledgerPath),archiveSuffix=`.${archiveSha256.slice(0,12)}.jsonl`,archiveName=`plan-ledger.reconcile-archive.${Date.now()}.${Math.floor(Math.random()*1e9)}${archiveSuffix}`,archivePath=path22.join(swarmDir,archiveName),archiveNeedsWrite=!0;for(let candidate of fs15.readdirSync(swarmDir)){if(!candidate.startsWith("plan-ledger.reconcile-archive.")||!candidate.endsWith(archiveSuffix))continue;let candidatePath=path22.join(swarmDir,candidate);if(fs15.readFileSync(candidatePath).equals(originalBytes)){archiveName=candidate,archivePath=candidatePath,archiveNeedsWrite=!1;break}}let archiveTempPath=`${archivePath}.tmp`,canonicalTempPath=`${ledgerPath}.reconcile.${Date.now()}.${Math.floor(Math.random()*1e9)}.tmp`,planHash=computePlanLedgerHash(validated),rawBadSuffix=findRawMalformedSuffix(originalBytes);if(rawBadSuffix.length===0)throw new LedgerStaleWriterError("Stale writer: raw ledger bytes no longer contain the malformed suffix detected during replay");let badSuffixSha256=crypto3.createHash("sha256").update(rawBadSuffix).digest("hex"),recoveryRoot={seq:1,timestamp:new Date().toISOString(),plan_id:derivePlanId(validated),event_type:"plan_created",source:"save_plan_truncated_ledger_reconcile",plan_hash_before:"",plan_hash_after:planHash,schema_version:LEDGER_SCHEMA_VERSION,payload:{plan:validated,payload_hash:planHash,recovery:{kind:"truncated_ledger_reconcile",archived_ledger:`.swarm/${archiveName}`,archived_sha256:archiveSha256,bad_suffix_sha256:badSuffixSha256,prior_tail_seq:expected.seq,prior_tail_hash:expected.ledgerHash}}};try{if(archiveNeedsWrite)_internals15.writeFileFsyncedThenRename(archiveTempPath,archivePath,originalBytes);_internals15.fsyncRecoveryDirectory(swarmDir),_internals15.writeFileFsyncedThenRename(canonicalTempPath,ledgerPath,`${JSON.stringify(recoveryRoot)}
|
|
223
223
|
`)}finally{for(let tempPath of[archiveTempPath,canonicalTempPath])try{fs15.unlinkSync(tempPath)}catch{}}return{archivePath,archiveSha256,recoveryRoot}})}async function replayFromLedger(directory,options){let{plan}=await replayFromLedgerWithStatus(directory,options);return plan}async function replayFromLedgerWithStatus(directory,_options){let{events,truncated,badSuffix}=await readLedgerEventsWithIntegrity(directory);if(events.length===0)return{plan:null,truncated,badSuffix};if(truncated&&badSuffix!==null)await quarantineLedgerSuffix(directory,badSuffix);return{plan:reconstructPlanFromEvents(directory,events),truncated,badSuffix}}function reconstructPlanFromEvents(directory,events){let targetPlanId=events[0].plan_id,relevantEvents=events.filter((e)=>e.plan_id===targetPlanId);{let snapshotEvents=relevantEvents.filter((e)=>e.event_type==="snapshot");if(snapshotEvents.length>0){let latestSnapshotEvent=snapshotEvents[snapshotEvents.length-1],plan2=latestSnapshotEvent.payload.plan,eventsAfterSnapshot=relevantEvents.filter((e)=>e.seq>latestSnapshotEvent.seq);for(let event of eventsAfterSnapshot)if(plan2=applyEventToPlan(plan2,event),plan2===null)return null;return plan2}}let createdEvent=relevantEvents.find((e)=>e.event_type==="plan_created");if(createdEvent?.payload&&typeof createdEvent.payload==="object"&&"plan"in createdEvent.payload){let parseResult=PlanSchema.safeParse(createdEvent.payload.plan);if(parseResult.success){let plan2=parseResult.data,eventsAfterCreated=relevantEvents.filter((e)=>e.seq>createdEvent.seq);for(let event of eventsAfterCreated){if(plan2===null)return null;plan2=applyEventToPlan(plan2,event)}return plan2}}let planJsonPath=getPlanJsonPath(directory);if(!fs15.existsSync(planJsonPath))return null;let plan;try{let content=fs15.readFileSync(planJsonPath,"utf8");plan=JSON.parse(content)}catch{return null}for(let event of relevantEvents){if(plan===null)return null;plan=applyEventToPlan(plan,event)}return plan}function applyEventToPlan(plan,event){switch(event.event_type){case"plan_created":if(event.payload&&typeof event.payload==="object"&&"plan"in event.payload){let parsed=PlanSchema.safeParse(event.payload.plan);if(parsed.success)return parsed.data}return plan;case"task_status_changed":if(event.task_id&&event.to_status){let parseResult=TaskStatusSchema.safeParse(event.to_status);if(!parseResult.success)return plan;for(let phase of plan.phases){let task=phase.tasks.find((t)=>t.id===event.task_id);if(task){task.status=parseResult.data;break}}}return plan;case"phase_completed":if(event.phase_id){let phase=plan.phases.find((p)=>p.id===event.phase_id);if(phase)phase.status="complete"}return plan;case"plan_exported":return plan;case"task_added":return plan;case"task_removed":if(event.task_id)for(let phase of plan.phases){let idx=phase.tasks.findIndex((t)=>t.id===event.task_id);if(idx!==-1){phase.tasks.splice(idx,1);break}}return plan;case"task_updated":return plan;case"plan_rebuilt":return plan;case"task_reordered":return plan;case"snapshot":return plan;case"plan_reset":return null;case"execution_profile_set":{let rawProfile=event.payload?.execution_profile;if(rawProfile!==void 0){let parsed=ExecutionProfileSchema.safeParse(rawProfile);if(parsed.success)return{...plan,execution_profile:parsed.data}}return plan}case"execution_profile_locked":{if(plan.execution_profile)return{...plan,execution_profile:{...plan.execution_profile,locked:!0}};return plan}default:throw Error(`applyEventToPlan: unhandled event type "${event.event_type}" at seq ${event.seq}`)}}async function readLedgerEventsWithIntegrity(directory,options){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return{events:[],truncated:!1,badSuffix:null};try{let lines=fs15.readFileSync(ledgerPath,"utf8").split(`
|
|
224
224
|
`),events=[],truncated=!1,badSuffix=null;for(let i=0;i<lines.length;i++){let line=lines[i];if(line.trim()==="")continue;try{let event=JSON.parse(line);events.push(event)}catch{truncated=!0,badSuffix=lines.slice(i).join(`
|
|
225
225
|
`);break}}return events.sort((a,b)=>a.seq-b.seq),{events,truncated,badSuffix}}catch(error49){if(options?.failClosedOnReadError)throw Error(`PLAN_LEDGER_UNREADABLE: ${ledgerPath} exists but could not be read (${error49 instanceof Error?error49.message:String(error49)}); plan state cannot be resolved. This is NOT an absent ledger — preserve the file and check permissions/filesystem health before retrying.`);return{events:[],truncated:!1,badSuffix:null}}}async function quarantineLedgerSuffix(directory,badSuffix){let salvagedCount=0;for(let line of badSuffix.split(`
|
|
226
|
-
`)){if(line.trim()==="")continue;try{JSON.parse(line),salvagedCount++}catch{}}try{assertProjectRoot(directory);let hash2=crypto3.createHash("sha256").update(badSuffix,"utf8").digest("hex").slice(0,12),swarmDir=path22.join(directory,".swarm");try{let existing=fs15.readdirSync(swarmDir).filter((name)=>name.startsWith("plan-ledger.quarantine.")&&name.endsWith(`.${hash2}`));for(let name of existing){let existingPath=path22.join(swarmDir,name);if(fs15.readFileSync(existingPath,"utf8")===badSuffix)return{path:existingPath,salvagedCount}}}catch{}let quarantinePath=path22.join(swarmDir,`plan-ledger.quarantine.${Date.now()}.${hash2}`);return fs15.writeFileSync(quarantinePath,badSuffix,"utf8"),log(`[ledger] Corrupted suffix quarantined to ${path22.relative(directory,quarantinePath)} (salvageable events: ${salvagedCount})`),{path:quarantinePath,salvagedCount}}catch{return{path:null,salvagedCount}}}async function loadLastApprovedPlan(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId)}async function loadLastPlanCriticApprovedSnapshot(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId,(payload)=>payload.approval?.source==="plan_critic_gate")}function findLastApprovedSnapshot(events,expectedPlanId,extraFilter){if(events.length===0)return null;for(let i=events.length-1;i>=0;i--){let event=events[i];if(event.event_type!=="snapshot")continue;if(event.source!=="critic_approved")continue;if(expectedPlanId!==void 0&&event.plan_id!==expectedPlanId)continue;let payload=event.payload;if(!payload||typeof payload!=="object"||!payload.plan)continue;if(expectedPlanId!==void 0){if(derivePlanId(payload.plan)!==expectedPlanId)continue}if(extraFilter&&!extraFilter(payload))continue;return{plan:payload.plan,seq:event.seq,timestamp:event.timestamp,approval:payload.approval,payloadHash:payload.payload_hash}}return null}var LEDGER_SCHEMA_VERSION="1.1.0",LEDGER_FILENAME="plan-ledger.jsonl",LEDGER_LOCK_PATH,PLAN_JSON_FILENAME="plan.json",LedgerStaleWriterError,_internals15;var init_ledger=__esm(()=>{init_plan_schema();init_lock();init_telemetry();init_logger();init_project_boundary();init_planning_profile();init_utils3();LEDGER_LOCK_PATH=path22.join(".swarm",LEDGER_FILENAME);LedgerStaleWriterError=class LedgerStaleWriterError extends Error{constructor(message){super(message);this.name="LedgerStaleWriterError"}};_internals15={computePlanHash,computePlanStructureHash,computeCurrentPlanHash,ledgerExists,getLatestLedgerSeq,readLedgerEvents,initLedger,appendLedgerEvent,appendLedgerEventWithRetry,takeSnapshotEvent,replayFromLedger,replayFromLedgerWithStatus,applyEventToPlan,readLedgerEventsWithIntegrity,quarantineLedgerSuffix,loadLastApprovedPlan,loadLastPlanCriticApprovedSnapshot,getLedgerPath,getPlanJsonPath,writeFileFsyncedThenRename,fsyncRecoveryDirectory,randomUUID:()=>crypto3.randomUUID()}});import{randomUUID as randomUUID4}from"node:crypto";import*as fs16 from"node:fs";import*as path23 from"node:path";function newIdentity(){return randomUUID4()}function isScopeBindingIdentity(value){return typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(value)}function canonicalWorkspaceIdentity(directory){try{let real=fs16.realpathSync(directory).replace(/\\/g,"/");return process.platform==="win32"?real.toLowerCase():real}catch{return null}}function isStrictTaskId2(value){return/^\d+\.\d+(?:\.\d+)*$/.test(value)}function normalizeScopePath(value){if(typeof value!=="string")return null;if(unsafePathTextReason(value))return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.includes("\x00")||trimmed.split("/").includes("..")||path23.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path23.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../"))return null;return normalized.endsWith("/")?normalized.slice(0,-1):normalized}function normalizeScopeFiles(files){if(!Array.isArray(files)||files.length===0||files.length>1e4)return null;let normalized=new Set,totalBytes=0;for(let file2 of files){let candidate=normalizeScopePath(file2);if(!candidate)return null;let bytes=Buffer.byteLength(candidate,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES||totalBytes>MAX_SCOPE_FILES_BYTES)return null;normalized.add(candidate)}return normalized.size>0?[...normalized].sort():null}function bindingKey(binding){return binding.generationId}function createScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),ttlMs=Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS);return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:derivePlanId(input.plan),planStructureHash:computePlanStructureHash(input.plan),taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:input.source,files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+ttlMs}}function sweepExpired(now=Date.now()){for(let[key,binding]of pendingScopeBindings)if(binding.expiresAt<=now){pendingScopeBindings.delete(key);let expired={...binding,revision:binding.revision+1,lifecycleState:"expired",updatedAt:now};scopeBindingTombstones.set(bindingKey(expired),expired)}while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function registerScopeBinding(binding){if(sweepExpired(),binding.lifecycleState!=="live"||binding.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"Only an unexpired live binding can be admitted."};let exact=pendingScopeBindings.get(bindingKey(binding));if(exact&&exact.bindingId!==binding.bindingId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"The generation identity collides with a different binding."};if(exact&&exact.revision>binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"A newer revision of this generation is already admitted."};if(binding.activation==="declaration"&&binding.dispatchCallId===void 0){for(let[existingKey,existing]of pendingScopeBindings)if(existing.generationId!==binding.generationId&&existing.activation==="declaration"&&existing.dispatchCallId===void 0&&existing.workspaceIdentity===binding.workspaceIdentity&&existing.taskId===binding.taskId&&existing.ownerSessionId===binding.ownerSessionId)pendingScopeBindings.delete(existingKey),scopeBindingTombstones.set(existingKey,{...existing,revision:existing.revision+1,lifecycleState:"superseded",updatedAt:Date.now()})}if(!exact&&pendingScopeBindings.size>=MAX_PENDING_SCOPE_BINDINGS)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:`Scope binding capacity ${MAX_PENDING_SCOPE_BINDINGS} is exhausted; complete or expire a live task before retrying.`};let key=bindingKey(binding);return pendingScopeBindings.delete(key),pendingScopeBindings.set(key,binding),{ok:!0,binding}}function getScopeBindingForParentDispatch(input){if(sweepExpired(),!input.parentSessionId.trim()||!input.dispatchCallId.trim())return null;let active=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.parentCallId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);if(active.length>1)return null;if(active.length===1)return active[0];let pending=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.ownerMessageId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);return pending.length===1?pending[0]:null}function createPrFeedbackScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!input.workflowSessionId.trim()||!input.workflowRevisionDigest.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),workflowIdentity=`pr-feedback:${input.workflowSessionId}`;return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:workflowIdentity,planStructureHash:input.workflowRevisionDigest,taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:"pr_feedback",files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS,workflowSessionId:input.workflowSessionId,workflowRevisionDigest:input.workflowRevisionDigest}}function getAuthorizedPrFeedbackScopeBinding(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return null;let matches=[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.source==="pr_feedback"&&binding.activation==="active"&&binding.ownerSessionId===input.activeSessionId&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&typeof binding.workflowSessionId==="string"&&binding.workflowSessionId===binding.parentOwnerSessionId&&typeof binding.workflowRevisionDigest==="string"&&binding.workflowRevisionDigest.length>0&&binding.planId===`pr-feedback:${binding.workflowSessionId}`&&binding.planStructureHash===binding.workflowRevisionDigest);return matches.length===1?matches[0]:null}function describeScopeWorkspaceMismatch(input){if(sweepExpired(),!input.activeSessionId.trim())return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity)return null;let first=[...pendingScopeBindings.values()].filter((binding)=>binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.source!=="pr_feedback"&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&binding.workspaceIdentity!==workspaceIdentity)[0];if(!first)return null;return`SCOPE_WORKSPACE_MISMATCH: an active scope binding for session "${sanitizeDiagnosticText(input.activeSessionId)}" (task ${first.taskId}, source ${first.source}) is rooted at "${sanitizeDiagnosticText(first.workspaceIdentity)}", but this gate resolved "${sanitizeDiagnosticText(workspaceIdentity)}". The gate is using the wrong workspace root for this session.`}function clearScopeBindings(predicate){let removed=[];if(!predicate)return removed.push(...pendingScopeBindings.values()),pendingScopeBindings.clear(),scopeBindingTombstones.clear(),removed;for(let[key,binding]of pendingScopeBindings)if(predicate(binding))removed.push(binding),pendingScopeBindings.delete(key);return removed}function clearExactScopeBinding(input){let candidate=pendingScopeBindings.get(input.generationId);if(!candidate||candidate.bindingId!==input.bindingId)return null;return pendingScopeBindings.delete(input.generationId),candidate}function installScopeBindingTombstone(binding){pendingScopeBindings.delete(binding.generationId),scopeBindingTombstones.delete(binding.generationId),scopeBindingTombstones.set(binding.generationId,binding);while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function hasScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live")}function hasDeliberateScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live"&&tombstone.lifecycleState!=="expired")}function clearSweepTombstoneForRevival(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);if(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.lifecycleState==="expired"&&tombstone.revision<=binding.revision)scopeBindingTombstones.delete(binding.generationId)}function installFailedRevocationOverlay(binding,reason){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||current.revision!==binding.revision)return!1;let now=Date.now();return installScopeBindingTombstone({...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)}),!0}function installScopeBindingRetirementIntent(binding){let source=pendingScopeBindings.get(binding.generationId)??(binding.version===2?binding:null);if(!source||source.bindingId!==binding.bindingId)return null;let now=Date.now(),tombstone={...source,revision:source.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(source.expiresAt,now)};return installScopeBindingTombstone(tombstone),tombstone}function updateExactScopeBinding(binding){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||binding.revision<=current.revision)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"The exact binding generation is stale or no longer active."};return pendingScopeBindings.set(binding.generationId,binding),{ok:!0,binding}}function createClaimedScopeBinding(previous,input){let now=Date.now();return{...previous,generationId:newIdentity(),revision:1,ownerSessionId:input.childSessionId,childSessionId:input.childSessionId,ownerMessageId:input.dispatchCallId,dispatchCallId:input.dispatchCallId,parentOwnerSessionId:input.parentSessionId,parentCallId:input.dispatchCallId,activation:"active",predecessorGenerationId:previous.generationId,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function deriveChildScopeBinding(parent,input){let workspaceIdentity=canonicalWorkspaceIdentity(input.childDirectory);if(!workspaceIdentity||!input.childSessionId.trim()||!input.parentCallId.trim())throw Error("Cannot derive child scope binding without verified identity");let now=Date.now();return{...parent,generationId:newIdentity(),revision:1,workspaceIdentity,ownerSessionId:input.childSessionId,ownerMessageId:input.parentCallId,dispatchCallId:input.parentCallId,activation:"active",parentOwnerSessionId:parent.ownerSessionId,parentCallId:input.parentCallId,predecessorGenerationId:parent.generationId,childSessionId:input.childSessionId,source:"worktree_derived",declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function scopeContains(scope,candidate){let flavor=getPathFlavor(),candidateIdentity=normalizePathIdentity(candidate,flavor).replace(/\\/g,"/");return scope.some((entry)=>{let entryIdentity=normalizePathIdentity(entry,flavor).replace(/\\/g,"/");return candidateIdentity===entryIdentity||candidateIdentity.startsWith(`${entryIdentity}/`)})}function isSubset(candidate,authority){return candidate.every((file2)=>scopeContains(authority,file2))}function resolveCoderScopeSources(input){let explicit=input.explicitFiles&&input.explicitFiles.length>0?normalizeScopeFiles(input.explicitFiles):null,plan=input.planFiles&&input.planFiles.length>0?normalizeScopeFiles(input.planFiles):null,directives=input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0?normalizeScopeFiles(input.fileDirectiveFiles):null;if(input.explicitFiles&&input.explicitFiles.length>0&&!explicit)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.planFiles&&input.planFiles.length>0&&!plan)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0&&!directives)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(explicit){let conflict=plan&&!isSubset(plan,explicit)?{source:"plan",files:plan}:directives&&!isSubset(directives,explicit)?{source:"file_directive",files:directives}:null;if(conflict)return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"declare_scope",authoritativeFiles:explicit,conflictingSource:conflict.source,conflictingFiles:conflict.files,disagreement:conflict.files.filter((file2)=>!scopeContains(explicit,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:explicit,source:"declare_scope"}}if(plan){if(directives&&!isSubset(directives,plan))return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"plan",authoritativeFiles:plan,conflictingSource:"file_directive",conflictingFiles:directives,disagreement:directives.filter((file2)=>!scopeContains(plan,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:plan,source:"plan"}}if(directives)return{ok:!0,files:directives,source:"file_directive"};return{ok:!1,code:"SCOPE_NOT_DECLARED"}}function renderSet(values,max=8){if(!values)return"(none)";return`${values.slice(0,max).map((value)=>JSON.stringify(value)).join(", ")}${values.length>max?`, … +${values.length-max}`:""}`}function formatCoderScopeConflict(decision){if(decision.code!=="SCOPE_CONFLICT")return"SCOPE_NOT_DECLARED: coder delegation has no complete, valid, non-empty scope.";return`SCOPE_CONFLICT: ${decision.authoritativeSource} authority [${renderSet(decision.authoritativeFiles)}] does not cover ${decision.conflictingSource} [${renderSet(decision.conflictingFiles)}]; outside authority: [${renderSet(decision.disagreement)}]. Architect: reconcile save_plan(files_touched), FILE directives, or declare_scope, then dispatch a new Task call.`}var MAX_PENDING_SCOPE_BINDINGS=256,DEFAULT_SCOPE_BINDING_TTL_MS=3600000,MAX_SCOPE_BINDING_TOMBSTONES=256,pendingScopeBindings,scopeBindingTombstones,MAX_SCOPE_PATH_BYTES=4096,MAX_SCOPE_FILES_BYTES=1048576;var init_scope_binding=__esm(()=>{init_ledger();init_utils3();init_path_identity();pendingScopeBindings=new Map,scopeBindingTombstones=new Map});var exports_scope_persistence={};__export(exports_scope_persistence,{writeScopeToDisk:()=>writeScopeToDisk,writeScopeBindingToDisk:()=>writeScopeBindingToDisk,tombstoneScopeBinding:()=>tombstoneScopeBinding,resolveScopeWithFallbacks:()=>resolveScopeWithFallbacks,resolveScopeBindingFromDisk:()=>resolveScopeBindingFromDisk,resolveAuthorizedScopeBindingForSessionDetailed:()=>resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBindingForSession:()=>resolveAuthorizedScopeBindingForSession,resolveAuthorizedScopeBindingDetailed:()=>resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBinding:()=>resolveAuthorizedScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk:()=>resolveAuthorizedPrFeedbackScopeBindingFromDisk,replaceExistingScopeDeclaration:()=>replaceExistingScopeDeclaration,refreshScopeBindingLease:()=>refreshScopeBindingLease,readScopeFromDisk:()=>readScopeFromDisk,readScopeBindingFromDisk:()=>readScopeBindingFromDisk,readPlanScope:()=>readPlanScope,pruneScopeBindingTombstones:()=>pruneScopeBindingTombstones,persistAndRegisterScopeBinding:()=>persistAndRegisterScopeBinding,flushScopeBindingMaintenance:()=>flushScopeBindingMaintenance,clearScopeForTask:()=>clearScopeForTask,clearScopeBindingFromDisk:()=>clearScopeBindingFromDisk,clearAllScopes:()=>clearAllScopes,claimScopeBindingForChildDurably:()=>claimScopeBindingForChildDurably,_scopePersistenceInternals:()=>_scopePersistenceInternals});import{createHash as createHash11}from"node:crypto";import*as fs17 from"node:fs";import*as path24 from"node:path";function lockSyncWithBoundedRetry(targetPath,attempts=41){let lastError;for(let attempt=0;attempt<attempts;attempt++)try{return lockfileWithSync.lockSync(targetPath,{stale:LOCK_STALE_MS2,realpath:!1})}catch(error49){if(lastError=error49,attempt+1<attempts)Atomics.wait(syncLockWait,0,0,25)}throw lastError instanceof Error?lastError:Error("Lock unavailable")}function getScopesDir(directory){return path24.join(directory,SCOPES_DIR)}function normalizePathForComparison(value){let normalized=path24.resolve(value);return process.platform==="win32"?normalized.toLowerCase():normalized}function isSafeTaskId(taskId){if(typeof taskId!=="string")return!1;if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(taskId))return!1;let head=taskId.replace(/\.+$/,"").split(".")[0].toUpperCase();if(WINDOWS_RESERVED.has(head))return!1;return!0}function isScopesDirSafe(directory,scopesDir){try{let resolvedWorkspace=fs17.realpathSync(directory),expectedSwarmDir=path24.join(resolvedWorkspace,".swarm"),expectedScopesDir=path24.join(expectedSwarmDir,"scopes"),swarmStat=fs17.lstatSync(expectedSwarmDir),scopesStat=fs17.lstatSync(expectedScopesDir);if(!swarmStat.isDirectory()||swarmStat.isSymbolicLink()||!scopesStat.isDirectory()||scopesStat.isSymbolicLink())return!1;let resolvedScopes=fs17.realpathSync(scopesDir);if(normalizePathForComparison(resolvedScopes)!==normalizePathForComparison(expectedScopesDir))return!1;let rel=path24.relative(resolvedWorkspace,resolvedScopes);return rel.length>0&&!rel.startsWith("..")&&!path24.isAbsolute(rel)}catch{return!1}}function resolveSafeScopeFileForUnlink(directory,targetPath){try{let resolvedWorkspace=fs17.realpathSync(directory),scopesDir=path24.join(resolvedWorkspace,SCOPES_DIR);if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let candidate=path24.resolve(targetPath),resolvedCandidate=fs17.realpathSync(candidate);if(normalizePathForComparison(path24.dirname(candidate))!==normalizePathForComparison(scopesDir)||normalizePathForComparison(resolvedCandidate)!==normalizePathForComparison(candidate))return null;let relative7=path24.relative(resolvedWorkspace,resolvedCandidate);if(relative7.length===0||relative7===".."||relative7.startsWith(`..${path24.sep}`)||path24.isAbsolute(relative7))return null;let leafStat=fs17.lstatSync(candidate);if(!leafStat.isFile()||leafStat.isSymbolicLink())return null;if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let finalResolvedCandidate=fs17.realpathSync(candidate),finalLeafStat=fs17.lstatSync(candidate);if(normalizePathForComparison(finalResolvedCandidate)!==normalizePathForComparison(candidate)||!finalLeafStat.isFile()||finalLeafStat.isSymbolicLink()||finalLeafStat.dev!==leafStat.dev||finalLeafStat.ino!==leafStat.ino)return null;return candidate}catch{return null}}function getScopeFilePath(directory,taskId){if(!isSafeTaskId(taskId))throw Error(`Invalid taskId for scope persistence: ${taskId}`);return path24.join(getScopesDir(directory),`scope-${taskId}.json`)}function getLegacyBindingFilePath(directory,taskId,ownerSessionId){if(!isSafeTaskId(taskId)||!ownerSessionId.trim())throw Error("Invalid identity for scope binding persistence");let ownerHash=createHash11("sha256").update(ownerSessionId).digest("hex").slice(0,24);return path24.join(getScopesDir(directory),`binding-${taskId}-${ownerHash}.json`)}function getBindingFilePath(directory,binding){if(!isSafeTaskId(binding.taskId)||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId))throw Error("Invalid exact identity for scope binding persistence");return path24.join(getScopesDir(directory),`binding-${binding.taskId}-${binding.bindingId}-${binding.generationId}.json`)}function getGenerationLockPath(bindingPath){return`${bindingPath}.generation-lock`}function getRetirementIntentPath(bindingPath){return`${bindingPath}.retirement-intent`}function hasDurableRetirementIntent(bindingPath,binding){let raw=readBoundedFile(getRetirementIntentPath(bindingPath));if(!raw)return!1;try{let intent=JSON.parse(raw);return intent.bindingId===binding.bindingId&&intent.generationId===binding.generationId}catch{return!1}}function ensureLockTargetSync(targetPath){try{let scopesDir=path24.dirname(targetPath),swarmDir=path24.dirname(scopesDir);if(path24.basename(scopesDir)!=="scopes"||path24.basename(swarmDir)!==".swarm")return!1;assertProjectRoot(path24.dirname(swarmDir)),fs17.mkdirSync(path24.dirname(targetPath),{recursive:!0});let nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(targetPath,fs17.constants.O_WRONLY|fs17.constants.O_CREAT|nofollow);return fs17.closeSync(fd),!0}catch{return!1}}function exactBindingPrefix(taskId){return`binding-${taskId}-`}function readBoundedFile(filePath){let nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(filePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile()||stat5.size<=0||stat5.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat5.size);return fs17.readSync(fd,buffer,0,stat5.size,0),buffer.toString("utf8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}}function deterministicIdentity(value){let hex3=createHash11("sha256").update(value).digest("hex").slice(0,32);return`${hex3.slice(0,8)}-${hex3.slice(8,12)}-4${hex3.slice(13,16)}-a${hex3.slice(17,20)}-${hex3.slice(20)}`}function validateScopeBindingPayload(directory,parsed,options={}){let workspaceIdentity=canonicalWorkspaceIdentity(directory),files=Array.isArray(parsed.files)?normalizeScopeFiles(parsed.files.filter((file2)=>typeof file2==="string")):null;if(parsed.version!==2||!workspaceIdentity||parsed.workspaceIdentity!==workspaceIdentity||!isSafeTaskId(parsed.taskId??"")||!files||typeof parsed.planId!=="string"||!parsed.planId||typeof parsed.planStructureHash!=="string"||!parsed.planStructureHash||typeof parsed.ownerSessionId!=="string"||!parsed.ownerSessionId.trim()||typeof parsed.ownerMessageId!=="string"||!parsed.ownerMessageId.trim()||!["declaration","pending_child","active"].includes(parsed.activation??"")||!["declare_scope","plan","file_directive","pr_feedback","worktree_derived"].includes(parsed.source??"")||typeof parsed.declaredAt!=="number"||!Number.isFinite(parsed.declaredAt)||typeof parsed.expiresAt!=="number"||!Number.isFinite(parsed.expiresAt))return null;let legacySeed=JSON.stringify({workspaceIdentity,planId:parsed.planId,planStructureHash:parsed.planStructureHash,taskId:parsed.taskId,ownerSessionId:parsed.ownerSessionId,ownerMessageId:parsed.ownerMessageId,dispatchCallId:parsed.dispatchCallId,activation:parsed.activation,source:parsed.source,files,declaredAt:parsed.declaredAt}),bindingId=isScopeBindingIdentity(parsed.bindingId)?parsed.bindingId:options.allowLegacy?deterministicIdentity(`binding\x00${legacySeed}`):null,generationId=isScopeBindingIdentity(parsed.generationId)?parsed.generationId:options.allowLegacy?deterministicIdentity(`generation\x00${legacySeed}`):null;if(!bindingId||!generationId)return null;let lifecycleState=parsed.lifecycleState??(options.allowLegacy?"live":void 0);if(!lifecycleState||!["live","expired","revoked","superseded"].includes(lifecycleState))return null;let revision=parsed.revision??(options.allowLegacy?1:void 0);if(!Number.isSafeInteger(revision)||(revision??0)<1)return null;let updatedAt=parsed.updatedAt??parsed.declaredAt,leaseStartedAt=parsed.leaseStartedAt??parsed.declaredAt;if(typeof updatedAt!=="number"||typeof leaseStartedAt!=="number")return null;let now=Date.now();if(parsed.declaredAt>now||updatedAt<parsed.declaredAt||leaseStartedAt<parsed.declaredAt||parsed.activation==="declaration"&&parsed.dispatchCallId!==void 0||parsed.activation==="pending_child"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId)||parsed.activation==="active"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId||typeof parsed.parentOwnerSessionId!=="string"||!parsed.parentOwnerSessionId||parsed.ownerSessionId===parsed.parentOwnerSessionId||parsed.parentCallId!==parsed.dispatchCallId))return null;return{...parsed,bindingId,generationId,revision,lifecycleState,files,workspaceIdentity,updatedAt,leaseStartedAt}}function exactFilenameMatches(filePath,binding){return normalizePathForComparison(filePath)===normalizePathForComparison(getBindingFilePath(binding.workspaceIdentity,binding))}function migrateLegacyBindingsSync(directory,scanCapacity=bindingFileScanCapacity){try{assertProjectRoot(directory)}catch{return!1}let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return!1;let names;try{names=fs17.readdirSync(scopesDir).sort()}catch{return!0}if(names.length>scanCapacity)return!1;for(let name of names){let match=/^binding-(.+)-([a-f0-9]{24})\.json$/i.exec(name);if(!match||!isSafeTaskId(match[1]))continue;let legacyPath=path24.join(scopesDir,name),releaseMigration;try{releaseMigration=lockfileWithSync.lockSync(legacyPath,{stale:LOCK_STALE_MS2,realpath:!1})}catch{return!1}try{let raw=readBoundedFile(legacyPath),binding=null;try{binding=raw?validateScopeBindingPayload(directory,JSON.parse(raw),{allowLegacy:!0}):null}catch{binding=null}let ownerHash=binding?createHash11("sha256").update(binding.ownerSessionId).digest("hex").slice(0,24):"",valid=binding&&binding.taskId===match[1]&&ownerHash.toLowerCase()===match[2].toLowerCase()&&normalizePathForComparison(getLegacyBindingFilePath(directory,binding.taskId,binding.ownerSessionId))===normalizePathForComparison(legacyPath),archiveDir=path24.join(scopesDir,"archive");fs17.mkdirSync(archiveDir,{recursive:!0});let archiveStat=fs17.lstatSync(archiveDir);if(!archiveStat.isDirectory()||archiveStat.isSymbolicLink())return!1;let archiveDigest=createHash11("sha256").update(raw??name).digest("hex").slice(0,32);if(valid&&binding){let exactPath=getBindingFilePath(directory,binding);if(!fs17.existsSync(exactPath))atomicWriteSwarmFileSync(exactPath,JSON.stringify(binding,null,2));else{let existingRaw=readBoundedFile(exactPath),existing=existingRaw?validateScopeBindingPayload(directory,JSON.parse(existingRaw)):null;if(!existing||existing.bindingId!==binding.bindingId||existing.generationId!==binding.generationId)return!1}}let archivePath=path24.join(archiveDir,`${valid?"migrated":"quarantined"}-${archiveDigest}.json`);if(!fs17.existsSync(archivePath))fs17.renameSync(legacyPath,archivePath);else fs17.unlinkSync(legacyPath);fs17.writeFileSync(`${archivePath}.receipt.json`,JSON.stringify({version:1,legacyName:name,result:valid?"migrated":"quarantined",bindingId:binding?.bindingId,generationId:binding?.generationId},null,2));let archiveEntries=fs17.readdirSync(archiveDir).sort();for(let stale of archiveEntries.slice(0,Math.max(0,archiveEntries.length-2*MAX_DURABLE_TOMBSTONES))){let stalePath=path24.join(archiveDir,stale);try{let stat5=fs17.lstatSync(stalePath);if(stat5.isFile()&&!stat5.isSymbolicLink())fs17.unlinkSync(stalePath)}catch{}}}catch{return!1}finally{try{releaseMigration?.()}catch{}}}return!0}async function writeScopeToDisk(directory,taskId,files,ttlMs=DEFAULT_TTL_MS){if(!isSafeTaskId(taskId))return;if(!Array.isArray(files)||files.length===0)return;if(files.length>MAX_FILES_PER_SCOPE)return;try{assertProjectRoot(directory)}catch{return}let scopesDir=getScopesDir(directory),scopePath=getScopeFilePath(directory,taskId);try{fs17.mkdirSync(scopesDir,{recursive:!0})}catch{return}if(!isScopesDirSafe(directory,scopesDir))return;let now=Date.now(),payload={version:SCOPE_SCHEMA_VERSION,taskId,declaredAt:now,expiresAt:now+ttlMs,files:[...files]},content=JSON.stringify(payload,null,2);try{let flags=fs17.constants.O_WRONLY|fs17.constants.O_CREAT,nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(scopePath,flags|nofollow);fs17.closeSync(fd)}catch{return}let release;try{let lockPath=getGenerationLockPath(scopePath);if(!await ensureLockTarget(lockPath))return;release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),await atomicWrite(scopePath,content)}catch{}finally{if(release)try{await release()}catch{}}}async function writeScopeBindingToDisk(directory,binding){try{assertProjectRoot(directory)}catch(error49){return persistenceFailure(`Scope persistence project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}if(!isSafeTaskId(binding.taskId)||binding.version!==2)return persistenceFailure("Invalid binding schema or task identity.");let workspaceIdentity=canonicalWorkspaceIdentity(directory),files=normalizeScopeFiles(binding.files);if(!workspaceIdentity||workspaceIdentity!==binding.workspaceIdentity||!files||!binding.ownerSessionId||!binding.ownerMessageId||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId)||binding.revision<1||binding.lifecycleState==="live"&&binding.expiresAt<=Date.now())return persistenceFailure("Binding identity, workspace, scope, or lease is invalid.");let scopesDir=getScopesDir(directory),scopePath=getBindingFilePath(directory,binding);try{fs17.mkdirSync(scopesDir,{recursive:!0})}catch{return persistenceFailure("Could not create the durable scope store.")}if(!isScopesDirSafe(directory,scopesDir))return persistenceFailure("The durable scope store failed containment checks.");let content=JSON.stringify({...binding,files},null,2);try{let flags=fs17.constants.O_WRONLY|fs17.constants.O_CREAT,nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(scopePath,flags|nofollow);fs17.closeSync(fd)}catch{return persistenceFailure("Could not create the exact generation record.")}let release;try{let lockPath=getGenerationLockPath(scopePath);if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare exact generation lock.");release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),await atomicWrite(scopePath,content);let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(directory,JSON.parse(verifiedRaw)):null;if(!verified||verified.bindingId!==binding.bindingId||verified.generationId!==binding.generationId||verified.revision!==binding.revision)return persistenceFailure("Exact generation verification failed after write.");return{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Exact generation write failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function persistenceFailure(message){return{ok:!1,code:"SCOPE_BINDING_PERSISTENCE_FAILED",message}}async function persistAndRegisterScopeBinding(directory,binding){let persisted=await writeScopeBindingToDisk(directory,binding);if(!persisted.ok)return persisted;let admission=registerScopeBinding(persisted.value);if(admission.ok)return scheduleScopeBindingMaintenance(directory),{ok:!0,value:persisted.value};let rollback=await tombstoneScopeBinding(directory,persisted.value,"superseded");return{ok:!1,code:rollback.ok?admission.code:"SCOPE_BINDING_PERSISTENCE_FAILED",message:rollback.ok?admission.message:`Memory admission failed and rollback failed: ${rollback.message}`}}function readScopeBindingFromDisk(input){let resolved=resolveScopeBindingFromDisk({...input,includeExpired:!1});return resolved.status==="found"?resolved.binding:null}function resolveScopeBindingFromDisk(input){if(!isSafeTaskId(input.taskId))return{status:"not_declared"};let completeSet=readAllExactBindings(input.directory);if(!completeSet)return scheduleScopeBindingMaintenance(input.directory),{status:"overloaded"};let candidates=completeSet.filter((parsed)=>parsed.taskId===input.taskId&&parsed.planId===derivePlanId(input.plan)&&parsed.planStructureHash===computePlanStructureHash(input.plan)&&parsed.ownerSessionId===input.ownerSessionId&&(input.requireDispatchCorrelation!==!0||isDispatchCorrelated(parsed))&&(input.requireDeclaration!==!0||parsed.activation==="declaration"&&parsed.dispatchCallId===void 0)&&(input.parentCallId===void 0||parsed.parentCallId===input.parentCallId)),live=candidates.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now());if(live.length>1)return{status:"ambiguous",candidates:live.slice(0,8),totalCandidates:live.length};if(live.length===1)return{status:"found",binding:live[0]};let expired=candidates.filter((candidate)=>candidate.lifecycleState!=="live"||candidate.expiresAt<=Date.now());return input.includeExpired&&expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expired.length}:{status:"not_declared"}}function isDispatchCorrelated(binding){return binding.activation==="active"&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId}function clearScopeBindingFromDisk(input){let localRetirement=installScopeBindingRetirementIntent(input.binding);try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope retirement project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let release;try{let resolvedWorkspace=fs17.realpathSync(input.directory),scopePath=getBindingFilePath(resolvedWorkspace,input.binding);if(!isScopesDirSafe(resolvedWorkspace,getScopesDir(resolvedWorkspace)))return persistenceFailure("The durable scope store failed containment checks.");let retirementIntentPath=getRetirementIntentPath(scopePath);atomicWriteSync(retirementIntentPath,JSON.stringify({version:1,bindingId:input.binding.bindingId,generationId:input.binding.generationId,createdAt:Date.now()})),scheduleScopeBindingMaintenance(resolvedWorkspace);let lockPath=getGenerationLockPath(scopePath);if(!ensureLockTargetSync(lockPath))return persistenceFailure("Could not prepare exact retirement lock.");release=lockSyncWithBoundedRetry(lockPath);let raw=readBoundedFile(scopePath);if(!raw){try{fs17.unlinkSync(retirementIntentPath)}catch{}return localRetirement?{ok:!0,value:localRetirement}:persistenceFailure("Exact generation disappeared before serialized retirement.")}let current=validateScopeBindingPayload(resolvedWorkspace,JSON.parse(raw));if(!current||current.bindingId!==input.binding.bindingId||current.generationId!==input.binding.generationId)return persistenceFailure("Exact generation identity changed before serialized retirement.");if(current.lifecycleState!=="live"){installScopeBindingTombstone(current);try{fs17.unlinkSync(retirementIntentPath)}catch{}return{ok:!0,value:current}}let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(current.expiresAt,now)};atomicWriteSync(scopePath,JSON.stringify(tombstone,null,2));let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(resolvedWorkspace,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==tombstone.revision||verified.lifecycleState!=="revoked")return persistenceFailure("Serialized retirement verification failed.");installScopeBindingTombstone(verified);try{fs17.unlinkSync(retirementIntentPath)}catch{}return scheduleScopeBindingMaintenance(resolvedWorkspace),{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Serialized retirement failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{try{release?.()}catch{}}}async function tombstoneScopeBinding(directory,binding,reason){let currentPath=getBindingFilePath(directory,binding),generationLockPath=getGenerationLockPath(currentPath);if(!await ensureLockTarget(generationLockPath))return installFailedRevocationOverlay(binding,reason),persistenceFailure("Could not prepare exact generation lock.");let release;try{release=await import_proper_lockfile3.default.lock(generationLockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1});let raw=readBoundedFile(currentPath);if(!raw)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Exact generation disappeared before tombstone.");let current=validateScopeBindingPayload(directory,JSON.parse(raw));if(!current||current.bindingId!==binding.bindingId||current.generationId!==binding.generationId)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Exact generation identity changed before tombstone.");if(current.revision!==binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Tombstone CAS revision is stale."};if(current.lifecycleState!=="live")return{ok:!0,value:current};let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)};await atomicWrite(currentPath,JSON.stringify(tombstone,null,2));let verifiedRaw=readBoundedFile(currentPath),verified=verifiedRaw?validateScopeBindingPayload(directory,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==tombstone.revision||verified.lifecycleState!==reason)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Tombstone verification failed.");return clearExactScopeBinding(binding),installScopeBindingTombstone(verified),scheduleScopeBindingMaintenance(directory),{ok:!0,value:verified}}catch(error49){return installFailedRevocationOverlay(binding,reason),persistenceFailure(`Tombstone failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}async function ensureLockTarget(targetPath){return ensureLockTargetSync(targetPath)}async function refreshScopeBindingLease(input){let scopePath;try{scopePath=getBindingFilePath(input.directory,input)}catch{return persistenceFailure("Invalid refresh identity.")}let generationLockPath=getGenerationLockPath(scopePath),createdGenerationLockTarget=!fs17.existsSync(generationLockPath);if(!await ensureLockTarget(generationLockPath))return persistenceFailure("Could not prepare refresh lock.");let release;try{if(release=await import_proper_lockfile3.default.lock(generationLockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),hasDurableRetirementIntent(scopePath,input))return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Refresh cannot renew a generation with durable retirement intent."};let raw=readBoundedFile(scopePath),current=raw?validateScopeBindingPayload(input.directory,JSON.parse(raw)):null;if(!current||current.bindingId!==input.bindingId||current.generationId!==input.generationId||current.taskId!==input.taskId||current.ownerSessionId!==input.activeSessionId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Refresh identity is not the exact current session/task generation."};if(current.lifecycleState!=="live"||current.expiresAt<=Date.now()||current.revision!==input.expectedRevision)return{ok:!1,code:current.expiresAt<=Date.now()?"SCOPE_BINDING_EXPIRED":"SCOPE_BINDING_STALE",message:"Refresh cannot renew an expired, tombstoned, or stale generation."};let now=Date.now(),refreshed={...current,revision:current.revision+1,updatedAt:now,leaseStartedAt:now,expiresAt:now+Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS)};await atomicWrite(scopePath,JSON.stringify(refreshed,null,2));let verifyRaw=readBoundedFile(scopePath),verified=verifyRaw?validateScopeBindingPayload(input.directory,JSON.parse(verifyRaw)):null;if(!verified||verified.revision!==refreshed.revision||verified.expiresAt!==refreshed.expiresAt)return persistenceFailure("Refreshed lease verification failed.");return updateExactScopeBinding(verified),{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Lease refresh failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}if(createdGenerationLockTarget&&!fs17.existsSync(scopePath))try{fs17.unlinkSync(generationLockPath)}catch{}}}function claimBaseName(binding){return`claim-${createHash11("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.dispatchCallId??""}`).digest("hex").slice(0,40)}`}function readAllExactBindings(directory,options={}){let scopesDir=getScopesDir(directory);try{fs17.lstatSync(scopesDir)}catch(error49){return error49.code==="ENOENT"?[]:null}if(!isScopesDirSafe(directory,scopesDir))return null;let scanCapacity=options.maintenanceScan?maintenanceFileScanCapacity:bindingFileScanCapacity;if(!migrateLegacyBindingsSync(directory,scanCapacity))return null;let names;try{names=fs17.readdirSync(scopesDir).sort()}catch{return[]}if(names.length>scanCapacity)return null;let bindings=[];for(let name of names){if(!name.startsWith("binding-")||!name.endsWith(".json"))continue;let filePath=path24.join(scopesDir,name),raw=readBoundedFile(filePath);if(!raw)continue;try{let binding=validateScopeBindingPayload(directory,JSON.parse(raw));if(binding&&exactFilenameMatches(filePath,binding))if(hasDurableRetirementIntent(filePath,binding)){let createdAt=Date.now();try{let rawIntent=readBoundedFile(getRetirementIntentPath(filePath)),parsedIntent=rawIntent?JSON.parse(rawIntent):null;if(typeof parsedIntent?.createdAt==="number")createdAt=parsedIntent.createdAt}catch{}bindings.push({...binding,lifecycleState:"revoked",updatedAt:createdAt,expiresAt:Math.min(binding.expiresAt,createdAt)})}else bindings.push(binding)}catch{}}let liveCount=bindings.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()).length;if(options.enforceLiveCapacity!==!1&&liveCount>liveBindingCapacity)return null;return bindings}async function claimScopeBindingForChildDurably(input){if(!input.parentSessionId.trim()||!input.childSessionId.trim()||!input.dispatchCallId.trim()||input.parentSessionId===input.childSessionId)return persistenceFailure("Claim requires distinct non-empty parent/child identities and an exact dispatch call.");let initial=readAllExactBindings(input.directory);if(!initial)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The complete durable binding set could not be evaluated."};let pending=initial.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.ownerMessageId===input.dispatchCallId);if(pending.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple pending generations match this exact Task dispatch."};let predecessor=pending[0];if(!predecessor){let successors=initial.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.predecessorGenerationId);if(successors.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple active successors match this Task dispatch."};let existing=successors[0];if(existing?.ownerSessionId===input.childSessionId){let admission=registerScopeBinding(existing);return admission.ok?{ok:!0,value:{previous:existing,claimed:existing}}:{ok:!1,code:admission.code,message:admission.message}}return existing?{ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This Task dispatch was already claimed by a different child session."}:initial.some((candidate)=>candidate.ownerSessionId===input.parentSessionId&&candidate.dispatchCallId===input.dispatchCallId)?{ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"No live pending generation remains for this Task dispatch."}:{ok:!1,code:"SCOPE_NOT_DECLARED",message:"No pending generation matches this Task dispatch."}}let claimPath=path24.join(getScopesDir(input.directory),`${claimBaseName(predecessor)}.json`);if(!await ensureLockTarget(claimPath))return persistenceFailure("Could not prepare the stable predecessor claim lock.");let release;try{release=await import_proper_lockfile3.default.lock(claimPath,{stale:LOCK_STALE_MS2,retries:{retries:5,minTimeout:50,maxTimeout:250},realpath:!1});let currentSet=readAllExactBindings(input.directory);if(!currentSet)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set became incomplete during claim."};let currentPredecessor=currentSet.find((binding)=>binding.generationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId),allSuccessors=currentSet.filter((binding)=>binding.predecessorGenerationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId),successors=allSuccessors.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now());if(successors.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Incompatible successors exist for one predecessor generation."};let receiptRaw=readBoundedFile(claimPath),receipt=null;if(receiptRaw)try{let parsed=JSON.parse(receiptRaw);if(parsed.version!==1||parsed.predecessorGenerationId!==predecessor.generationId||!isScopeBindingIdentity(parsed.winnerGenerationId)||typeof parsed.childSessionId!=="string"||parsed.dispatchCallId!==input.dispatchCallId)return persistenceFailure("Claim winner receipt is malformed or belongs to another predecessor.");receipt=parsed}catch{return persistenceFailure("Claim winner receipt is malformed.")}if(receipt){let receiptWinner=allSuccessors.find((candidate)=>candidate.generationId===receipt?.winnerGenerationId);if(!receiptWinner)return persistenceFailure("Claim receipt has no verified successor; pending remains fail-closed for restart reconciliation.");if(receiptWinner.lifecycleState!=="live"||receiptWinner.expiresAt<=Date.now())fs17.writeFileSync(claimPath,""),receipt=null}if(receipt&&successors[0]&&receipt.winnerGenerationId!==successors[0].generationId)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Claim receipt and durable successor disagree."};let existing=successors[0];if(existing){if(existing.ownerSessionId!==input.childSessionId)return{ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This pending generation has a winner in another child session."};if(await writeClaimReceipt(claimPath,predecessor,existing,input),currentPredecessor?.lifecycleState==="live")await tombstoneScopeBinding(input.directory,currentPredecessor,"superseded");let admission2=registerScopeBinding(existing);return admission2.ok?{ok:!0,value:{previous:predecessor,claimed:existing}}:{ok:!1,code:admission2.code,message:admission2.message}}if(!currentPredecessor||currentPredecessor.lifecycleState!=="live"||currentPredecessor.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"The pending predecessor expired before claim."};predecessor=currentPredecessor;let claimed=createClaimedScopeBinding(predecessor,input),persisted=await writeScopeBindingToDisk(input.directory,claimed);if(!persisted.ok)return persisted;let receiptWrite=await writeClaimReceipt(claimPath,predecessor,persisted.value,input);if(!receiptWrite.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),receiptWrite;let admission=registerScopeBinding(persisted.value);if(!admission.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),{ok:!1,code:admission.code,message:admission.message};let retired=await tombstoneScopeBinding(input.directory,predecessor,"superseded");if(!retired.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),persistenceFailure(`Successor was persisted but predecessor retirement failed: ${retired.message}`);return{ok:!0,value:{previous:predecessor,claimed:persisted.value}}}catch(error49){return persistenceFailure(`Claim transaction failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}async function writeClaimReceipt(claimPath,previous,claimed,input){let receipt={version:1,predecessorGenerationId:previous.generationId,winnerGenerationId:claimed.generationId,childSessionId:input.childSessionId,dispatchCallId:input.dispatchCallId,createdAt:Date.now()};try{await atomicWrite(claimPath,JSON.stringify(receipt,null,2));let raw=readBoundedFile(claimPath),verified=raw?JSON.parse(raw):null;return verified?.winnerGenerationId===receipt.winnerGenerationId&&verified.childSessionId===receipt.childSessionId?{ok:!0,value:verified}:persistenceFailure("Claim winner receipt verification failed.")}catch(error49){return persistenceFailure(`Claim winner receipt write failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}}async function replaceExistingScopeDeclaration(input){try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope declaration project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let{binding}=input;if(binding.activation!=="declaration"||binding.dispatchCallId!==void 0)return persistenceFailure("declare_scope may persist only a declaration generation.");let digest2=createHash11("sha256").update(`${binding.workspaceIdentity}\x00${binding.taskId}\x00${binding.ownerSessionId}`).digest("hex").slice(0,40),lockPath=path24.join(getScopesDir(input.directory),`declaration-${digest2}.lock-target`);if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare declaration transaction lock.");let release;try{release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:5,minTimeout:50,maxTimeout:250},realpath:!1});let all=readAllExactBindings(input.directory);if(!all)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set cannot be completely evaluated."};let owned=all.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now()&&candidate.workspaceIdentity===binding.workspaceIdentity&&candidate.taskId===binding.taskId&&candidate.ownerSessionId===binding.ownerSessionId&&candidate.generationId!==binding.generationId);if(owned.length>0&&!input.replaceExisting)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"A live owned generation already exists; retry declare_scope with replace_existing=true to revoke it atomically."};let persisted=await writeScopeBindingToDisk(input.directory,binding);if(!persisted.ok)return persisted;for(let prior of owned){let retired=await tombstoneScopeBinding(input.directory,prior,"superseded");if(!retired.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),persistenceFailure(`Replacement could not retire generation ${prior.generationId}: ${retired.message}`)}let admission=registerScopeBinding(persisted.value);if(!admission.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),{ok:!1,code:admission.code,message:admission.message};return{ok:!0,value:persisted.value}}catch(error49){return persistenceFailure(`Declaration transaction failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function scheduleScopeBindingMaintenance(directory){let key=normalizePathForComparison(directory);if(maintenanceJobs.has(key))return;while(maintenanceJobs.size>=MAX_MAINTENANCE_JOBS){let oldest=maintenanceJobs.keys().next().value;if(!oldest)break;maintenanceJobs.delete(oldest)}let job=Promise.resolve().then(()=>pruneScopeBindingTombstones(directory)).then(()=>{return}).catch(()=>{return}).finally(()=>maintenanceJobs.delete(key));maintenanceJobs.set(key,job)}async function flushScopeBindingMaintenance(directory){let key=directory?normalizePathForComparison(directory):void 0,job=key?maintenanceJobs.get(key):void 0;await Promise.all(job?[job]:[...maintenanceJobs.values()])}async function pruneScopeBindingTombstones(directory){let lockPath=path24.join(getScopesDir(directory),"maintenance.lock-target");if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare scope maintenance lock.");let release;try{release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1});let all=readAllExactBindings(directory,{enforceLiveCapacity:!1,maintenanceScan:!0});if(!all)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set cannot be completely evaluated."};for(let binding of all){let filePath=getBindingFilePath(directory,binding);if(!hasDurableRetirementIntent(filePath,binding))continue;if((await tombstoneScopeBinding(directory,binding,"revoked")).ok)try{fs17.unlinkSync(getRetirementIntentPath(filePath))}catch{}}if(all=readAllExactBindings(directory,{enforceLiveCapacity:!1,maintenanceScan:!0}),!all)return persistenceFailure("The durable binding set changed during maintenance reconciliation.");let tombstones=all.filter((binding)=>binding.lifecycleState!=="live").sort((left,right)=>left.updatedAt-right.updatedAt),now=Date.now(),removable=tombstones.filter((binding,index)=>now-binding.updatedAt>MAX_TOMBSTONE_AGE_MS||index<tombstones.length-MAX_DURABLE_TOMBSTONES),removed=0;for(let binding of removable){let filePath=resolveSafeScopeFileForUnlink(directory,getBindingFilePath(directory,binding));if(!filePath)continue;let exactLockPath=getGenerationLockPath(filePath);if(!await ensureLockTarget(exactLockPath))continue;let releaseExact,removedExact=!1;try{releaseExact=await import_proper_lockfile3.default.lock(exactLockPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let latestRaw=readBoundedFile(filePath),latest=latestRaw?validateScopeBindingPayload(directory,JSON.parse(latestRaw)):null;if(!latest||latest.generationId!==binding.generationId||latest.revision!==binding.revision||latest.lifecycleState==="live"&&!hasDurableRetirementIntent(filePath,latest))continue;fs17.unlinkSync(filePath),removedExact=!0,removed++}catch{}finally{if(releaseExact)try{await releaseExact()}catch{}}if(removedExact&&!fs17.existsSync(filePath)){try{fs17.unlinkSync(exactLockPath)}catch{}try{fs17.unlinkSync(getRetirementIntentPath(filePath))}catch{}}}let receiptNames=[];try{receiptNames=fs17.readdirSync(getScopesDir(directory)).filter((name)=>/^claim-[a-f0-9]{40}\.json$/i.test(name)).slice(0,MAX_BINDING_FILES_TO_SCAN)}catch{}for(let name of receiptNames){let receiptPath=path24.join(getScopesDir(directory),name),releaseReceipt;try{releaseReceipt=await import_proper_lockfile3.default.lock(receiptPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let raw=readBoundedFile(receiptPath);if(!raw)continue;let receipt=null;try{receipt=JSON.parse(raw)}catch{}let winner=receipt?all.find((binding)=>binding.generationId===receipt?.winnerGenerationId):void 0;if(Date.now()-fs17.statSync(receiptPath).mtimeMs>MAX_TOMBSTONE_AGE_MS||Boolean(winner&&(winner.lifecycleState!=="live"||winner.expiresAt<=Date.now())))fs17.unlinkSync(receiptPath),removed++}catch{}finally{if(releaseReceipt)try{await releaseReceipt()}catch{}}}return{ok:!0,value:removed}}catch(error49){return persistenceFailure(`Scope maintenance failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function readCurrentPlan(directory){try{let planPath=path24.join(directory,".swarm","plan.json"),stat5=fs17.statSync(planPath);if(!stat5.isFile()||stat5.size>MAX_PLAN_BYTES)return null;let parsed=PlanSchema.safeParse(JSON.parse(fs17.readFileSync(planPath,"utf8")));return parsed.success?parsed.data:null}catch{return null}}function appendScopeBindingRevivalEvent(workspace,revived){try{appendCoreEventSync(workspace,{type:"scope_binding_auto_recovered",timestamp:new Date().toISOString(),taskId:revived.taskId,sessionId:revived.ownerSessionId,generationId:revived.generationId,revision:revived.revision,expiresAt:new Date(revived.expiresAt).toISOString()})}catch{}}function attemptIdleScopeBindingRevival(directory,resolution){if(resolution.status!=="expired")return null;if(resolution.totalCandidates!==1||resolution.candidates.length!==1)return null;let candidate=resolution.candidates[0];if(!candidate)return null;let now=Date.now();if(candidate.lifecycleState!=="live")return null;if(candidate.expiresAt>now)return null;if(now-candidate.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;if(hasDeliberateScopeBindingDenyOverlay(candidate))return null;let release;try{let resolvedWorkspace=fs17.realpathSync(directory);assertProjectRoot(resolvedWorkspace);let scopePath=getBindingFilePath(resolvedWorkspace,candidate);if(!isScopesDirSafe(resolvedWorkspace,getScopesDir(resolvedWorkspace)))return null;let lockPath=getGenerationLockPath(scopePath);if(!ensureLockTargetSync(lockPath))return null;release=lockSyncWithBoundedRetry(lockPath);let raw=readBoundedFile(scopePath);if(!raw)return null;let current=validateScopeBindingPayload(resolvedWorkspace,JSON.parse(raw));if(!current||current.bindingId!==candidate.bindingId||current.generationId!==candidate.generationId||current.revision!==candidate.revision||current.lifecycleState!=="live"||current.expiresAt>Date.now()||Date.now()-current.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;let revivedAt=Date.now(),revived={...current,revision:current.revision+1,updatedAt:revivedAt,leaseStartedAt:revivedAt,expiresAt:revivedAt+DEFAULT_SCOPE_BINDING_TTL_MS};atomicWriteSync(scopePath,JSON.stringify(revived,null,2));let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(resolvedWorkspace,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==revived.revision||verified.lifecycleState!=="live"||verified.expiresAt!==revived.expiresAt)return null;return clearSweepTombstoneForRevival(revived),appendScopeBindingRevivalEvent(resolvedWorkspace,revived),revived}catch{return null}finally{if(release)try{release()}catch{}}}function resolveAuthorizedScopeBindingForPlan(input){let resolution=resolveAuthorizedScopeBindingForPlanDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForPlanDetailed(input){let durable=resolveScopeBindingFromDisk({directory:input.directory,taskId:input.taskId,plan:input.plan,ownerSessionId:input.activeSessionId,requireDispatchCorrelation:!0,includeExpired:!0});if(durable.status==="found"){if(hasScopeBindingDenyOverlay(durable.binding))return{status:"expired",candidates:[durable.binding],totalCandidates:1};return registerScopeBinding(durable.binding).ok?durable:{status:"overloaded"}}if(durable.status==="expired"){let revived=attemptIdleScopeBindingRevival(input.directory,durable);if(revived){if(registerScopeBinding(revived).ok)return{status:"found",binding:revived}}}if(durable.status!=="not_declared")return durable;return{status:"not_declared"}}function resolveAuthorizedScopeBinding(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlan({...input,plan}):null}function resolveAuthorizedScopeBindingDetailed(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlanDetailed({...input,plan}):{status:"not_declared"}}function resolveAuthorizedScopeBindingForSession(input){let resolution=resolveAuthorizedScopeBindingForSessionDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForSessionDetailed(input){let plan=readCurrentPlan(input.directory);if(!plan)return{status:"not_declared"};let matches=[],expired=[],expiredTotal=0;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let resolution=resolveAuthorizedScopeBindingForPlanDetailed({directory:input.directory,plan,taskId:task.id,activeSessionId:input.activeSessionId});if(resolution.status==="overloaded")return resolution;if(resolution.status==="ambiguous")return resolution;if(resolution.status==="found")matches.push(resolution.binding);if(resolution.status==="expired")expired.push(...resolution.candidates),expiredTotal+=resolution.totalCandidates;if(matches.length>1)return{status:"ambiguous",candidates:matches.slice(0,8),totalCandidates:matches.length}}if(matches[0])return{status:"found",binding:matches[0]};return expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expiredTotal}:{status:"not_declared"}}function readPrFeedbackBindingFile(directory,filePath,activeSessionId,taskId){try{let leaf=fs17.lstatSync(filePath);if(!leaf.isFile()||leaf.isSymbolicLink())return null;if(normalizePathForComparison(fs17.realpathSync(filePath))!==normalizePathForComparison(filePath))return null}catch{return null}let nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(filePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}let raw="";try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile()||stat5.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat5.size);fs17.readSync(fd,buffer,0,stat5.size,0),raw=buffer.toString("utf8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}let parsed;try{parsed=validateScopeBindingPayload(directory,JSON.parse(raw))}catch{return null}if(!parsed)return null;if(hasScopeBindingDenyOverlay(parsed))return null;let now=Date.now();if(parsed.source!=="pr_feedback"||taskId!==void 0&&parsed.taskId!==taskId||parsed.ownerSessionId!==activeSessionId||parsed.activation!=="active"||typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId||typeof parsed.parentOwnerSessionId!=="string"||!parsed.parentOwnerSessionId||parsed.ownerSessionId===parsed.parentOwnerSessionId||parsed.parentCallId!==parsed.dispatchCallId||parsed.workflowSessionId!==parsed.parentOwnerSessionId||typeof parsed.workflowRevisionDigest!=="string"||!parsed.workflowRevisionDigest||parsed.planId!==`pr-feedback:${parsed.workflowSessionId}`||parsed.planStructureHash!==parsed.workflowRevisionDigest||parsed.declaredAt>now||parsed.expiresAt<=now||parsed.lifecycleState!=="live")return null;let expectedPath=getBindingFilePath(directory,parsed);if(normalizePathForComparison(expectedPath)!==normalizePathForComparison(filePath))return null;return parsed}function resolveAuthorizedPrFeedbackScopeBindingFromDisk(input){if(!input.activeSessionId.trim())return null;let scopesDir=getScopesDir(input.directory);if(!isScopesDirSafe(input.directory,scopesDir))return null;if(!migrateLegacyBindingsSync(input.directory))return null;let candidates;if(input.taskId){if(!isSafeTaskId(input.taskId))return null;try{let names=fs17.readdirSync(scopesDir);if(names.length>MAX_BINDING_FILES_TO_SCAN)return null;candidates=names.filter((name)=>name.startsWith(exactBindingPrefix(input.taskId))&&name.endsWith(".json")).map((name)=>path24.join(scopesDir,name))}catch{return null}}else try{let names=fs17.readdirSync(scopesDir);if(names.length>MAX_BINDING_FILES_TO_SCAN)return null;candidates=names.filter((name)=>name.startsWith("binding-")&&name.endsWith(".json")).map((name)=>path24.join(scopesDir,name))}catch{return null}let matches=candidates.map((candidate)=>readPrFeedbackBindingFile(input.directory,candidate,input.activeSessionId,input.taskId)).filter((binding)=>binding!==null);if(matches.length!==1)return null;return registerScopeBinding(matches[0]).ok?matches[0]:null}async function atomicWrite(targetPath,content){await atomicWriteSwarmFile(targetPath,content)}function atomicWriteSync(targetPath,content){atomicWriteSwarmFileSync(targetPath,content)}function readScopeFromDisk(directory,taskId){if(!isSafeTaskId(taskId))return null;let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return null;let scopePath=getScopeFilePath(directory,taskId),nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(scopePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}let raw;try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile())return null;if(stat5.size>MAX_SCOPE_BYTES)return null;let buf=Buffer.alloc(stat5.size);fs17.readSync(fd,buf,0,stat5.size,0),raw=buf.toString("utf-8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}if(!raw.trim())return null;let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(parsed.version!==SCOPE_SCHEMA_VERSION)return null;if(parsed.taskId!==taskId)return null;let now=Date.now();if(typeof parsed.declaredAt!=="number"||parsed.declaredAt>now)return null;if(typeof parsed.expiresAt!=="number"||now>=parsed.expiresAt)return null;if(!Array.isArray(parsed.files))return null;if(parsed.files.length>MAX_FILES_PER_SCOPE)return null;let files=parsed.files.filter((f)=>typeof f==="string");return files.length>0?files:null}function readPlanScope(directory,taskId){if(!isSafeTaskId(taskId))return null;try{let planPath=path24.join(directory,".swarm","plan.json"),stat5=fs17.statSync(planPath);if(!stat5.isFile())return null;if(stat5.size>MAX_PLAN_BYTES)return null;let raw=fs17.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);for(let phase of plan.phases??[])for(let task of phase.tasks??[]){if(task.id!==taskId)continue;let ft=task.files_touched;if(Array.isArray(ft)&&ft.length>0){if(ft.length>MAX_FILES_PER_SCOPE)return null;return ft.filter((f)=>typeof f==="string")}if(typeof ft==="string"&&ft.length>0)return[ft];return null}return null}catch{return null}}function clearScopeForTask(directory,taskId){if(!isSafeTaskId(taskId))return;try{assertProjectRoot(directory),fs17.unlinkSync(getScopeFilePath(directory,taskId))}catch{}}function clearAllScopes(directory){try{assertProjectRoot(directory),fs17.rmSync(getScopesDir(directory),{recursive:!0,force:!0})}catch{}}function resolveScopeWithFallbacks(input){let{directory,taskId,inMemoryScope,pendingMapScope}=input;if(inMemoryScope&&inMemoryScope.length>0)return inMemoryScope;if(taskId){let disk=readScopeFromDisk(directory,taskId);if(disk&&disk.length>0)return disk;let plan=readPlanScope(directory,taskId);if(plan&&plan.length>0)return plan}if(pendingMapScope&&pendingMapScope.length>0)return pendingMapScope;return null}var import_proper_lockfile3,SCOPE_SCHEMA_VERSION=1,DEFAULT_TTL_MS=86400000,LOCK_STALE_MS2=30000,SCOPES_DIR=".swarm/scopes",MAX_FILES_PER_SCOPE=1e4,MAX_PLAN_BYTES=10485760,MAX_SCOPE_BYTES=2097152,MAX_BINDING_FILES_TO_SCAN=1e4,MAX_TOMBSTONE_AGE_MS=604800000,MAX_DURABLE_TOMBSTONES=256,liveBindingCapacity,bindingFileScanCapacity,maintenanceFileScanCapacity,MAX_MAINTENANCE_JOBS=64,maintenanceJobs,lockfileWithSync,syncLockWait,WINDOWS_RESERVED,SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS=86400000,_scopePersistenceInternals;var init_scope_persistence=__esm(()=>{init_plan_schema();init_core_events();init_ledger();init_utils3();init_atomic_write();init_project_boundary();init_scope_binding();import_proper_lockfile3=__toESM(require_proper_lockfile(),1),liveBindingCapacity=MAX_PENDING_SCOPE_BINDINGS,bindingFileScanCapacity=MAX_BINDING_FILES_TO_SCAN,maintenanceFileScanCapacity=MAX_BINDING_FILES_TO_SCAN*2,maintenanceJobs=new Map,lockfileWithSync=import_proper_lockfile3.default,syncLockWait=new Int32Array(new SharedArrayBuffer(4));WINDOWS_RESERVED=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);_scopePersistenceInternals={get liveBindingCapacity(){return liveBindingCapacity},set liveBindingCapacity(value){liveBindingCapacity=Math.max(1,Math.floor(value))},get bindingFileScanCapacity(){return bindingFileScanCapacity},set bindingFileScanCapacity(value){bindingFileScanCapacity=Math.max(1,Math.floor(value))},get maintenanceFileScanCapacity(){return maintenanceFileScanCapacity},set maintenanceFileScanCapacity(value){maintenanceFileScanCapacity=Math.max(1,Math.floor(value))}}});var exports_core3={};__export(exports_core3,{writeLaneProfileToDiskReal:()=>writeLaneProfileToDiskReal,shortenWorktreePath:()=>shortenWorktreePath,resolveWorktreeBaseDir:()=>resolveWorktreeBaseDir,removeWorktree:()=>removeWorktree,removeLaneProfileFromDiskReal:()=>removeLaneProfileFromDiskReal,provisionWorktree:()=>provisionWorktree,makeWorktreeBranchName:()=>makeWorktreeBranchName,isPathUnderSwarmWorktreeBase:()=>isPathUnderSwarmWorktreeBase,isCleanWorktree:()=>isCleanWorktree,cleanUntrackedFiles:()=>cleanUntrackedFiles,checkPathBudget:()=>checkPathBudget,autoCommitDirty:()=>autoCommitDirty,assertCleanWorkingTree:()=>assertCleanWorkingTree,_internals:()=>_internals16});import*as fs18 from"node:fs";import*as fsPromises3 from"node:fs/promises";import*as os5 from"node:os";import*as path25 from"node:path";async function writeLaneProfileToDiskReal(worktreePath,laneIndex,envOverrides){let lines=[];for(let[key,value]of Object.entries(envOverrides)){if(value===null)continue;if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))continue;if(value.includes(`
|
|
226
|
+
`)){if(line.trim()==="")continue;try{JSON.parse(line),salvagedCount++}catch{}}try{assertProjectRoot(directory);let hash2=crypto3.createHash("sha256").update(badSuffix,"utf8").digest("hex").slice(0,12),swarmDir=path22.join(directory,".swarm");try{let existing=fs15.readdirSync(swarmDir).filter((name)=>name.startsWith("plan-ledger.quarantine.")&&name.endsWith(`.${hash2}`));for(let name of existing){let existingPath=path22.join(swarmDir,name);if(fs15.readFileSync(existingPath,"utf8")===badSuffix)return{path:existingPath,salvagedCount}}}catch{}let quarantinePath=path22.join(swarmDir,`plan-ledger.quarantine.${Date.now()}.${hash2}`);return fs15.writeFileSync(quarantinePath,badSuffix,"utf8"),log(`[ledger] Corrupted suffix quarantined to ${path22.relative(directory,quarantinePath)} (salvageable events: ${salvagedCount})`),{path:quarantinePath,salvagedCount}}catch{return{path:null,salvagedCount}}}async function loadLastApprovedPlan(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId)}async function loadLastPlanCriticApprovedSnapshot(directory,expectedPlanId){let events=await readLedgerEvents(directory);return findLastApprovedSnapshot(events,expectedPlanId,(payload)=>payload.approval?.source==="plan_critic_gate")}function findLastApprovedSnapshot(events,expectedPlanId,extraFilter){if(events.length===0)return null;for(let i=events.length-1;i>=0;i--){let event=events[i];if(event.event_type!=="snapshot")continue;if(event.source!=="critic_approved")continue;if(expectedPlanId!==void 0&&event.plan_id!==expectedPlanId)continue;let payload=event.payload;if(!payload||typeof payload!=="object"||!payload.plan)continue;if(expectedPlanId!==void 0){if(derivePlanId(payload.plan)!==expectedPlanId)continue}if(extraFilter&&!extraFilter(payload))continue;return{plan:payload.plan,seq:event.seq,timestamp:event.timestamp,approval:payload.approval,payloadHash:payload.payload_hash}}return null}var LEDGER_SCHEMA_VERSION="1.1.0",LEDGER_FILENAME="plan-ledger.jsonl",LEDGER_LOCK_PATH,PLAN_JSON_FILENAME="plan.json",LedgerStaleWriterError,_internals15;var init_ledger=__esm(()=>{init_plan_schema();init_lock();init_telemetry();init_logger();init_project_boundary();init_planning_profile();init_utils3();LEDGER_LOCK_PATH=path22.join(".swarm",LEDGER_FILENAME);LedgerStaleWriterError=class LedgerStaleWriterError extends Error{constructor(message){super(message);this.name="LedgerStaleWriterError"}};_internals15={computePlanLedgerHash,computePlanStructureHash,computeCurrentPlanHash,ledgerExists,getLatestLedgerSeq,readLedgerEvents,initLedger,appendLedgerEvent,appendLedgerEventWithRetry,takeSnapshotEvent,replayFromLedger,replayFromLedgerWithStatus,applyEventToPlan,readLedgerEventsWithIntegrity,quarantineLedgerSuffix,loadLastApprovedPlan,loadLastPlanCriticApprovedSnapshot,getLedgerPath,getPlanJsonPath,writeFileFsyncedThenRename,fsyncRecoveryDirectory,randomUUID:()=>crypto3.randomUUID()}});import{randomUUID as randomUUID4}from"node:crypto";import*as fs16 from"node:fs";import*as path23 from"node:path";function newIdentity(){return randomUUID4()}function isScopeBindingIdentity(value){return typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(value)}function canonicalWorkspaceIdentity(directory){try{let real=fs16.realpathSync(directory).replace(/\\/g,"/");return process.platform==="win32"?real.toLowerCase():real}catch{return null}}function isStrictTaskId2(value){return/^\d+\.\d+(?:\.\d+)*$/.test(value)}function normalizeScopePath(value){if(typeof value!=="string")return null;if(unsafePathTextReason(value))return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.includes("\x00")||trimmed.split("/").includes("..")||path23.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path23.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../"))return null;return normalized.endsWith("/")?normalized.slice(0,-1):normalized}function normalizeScopeFiles(files){if(!Array.isArray(files)||files.length===0||files.length>1e4)return null;let normalized=new Set,totalBytes=0;for(let file2 of files){let candidate=normalizeScopePath(file2);if(!candidate)return null;let bytes=Buffer.byteLength(candidate,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES||totalBytes>MAX_SCOPE_FILES_BYTES)return null;normalized.add(candidate)}return normalized.size>0?[...normalized].sort():null}function bindingKey(binding){return binding.generationId}function createScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),ttlMs=Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS);return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:derivePlanId(input.plan),planStructureHash:computePlanStructureHash(input.plan),taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:input.source,files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+ttlMs}}function sweepExpired(now=Date.now()){for(let[key,binding]of pendingScopeBindings)if(binding.expiresAt<=now){pendingScopeBindings.delete(key);let expired={...binding,revision:binding.revision+1,lifecycleState:"expired",updatedAt:now};scopeBindingTombstones.set(bindingKey(expired),expired)}while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function registerScopeBinding(binding){if(sweepExpired(),binding.lifecycleState!=="live"||binding.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"Only an unexpired live binding can be admitted."};let exact=pendingScopeBindings.get(bindingKey(binding));if(exact&&exact.bindingId!==binding.bindingId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"The generation identity collides with a different binding."};if(exact&&exact.revision>binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"A newer revision of this generation is already admitted."};if(binding.activation==="declaration"&&binding.dispatchCallId===void 0){for(let[existingKey,existing]of pendingScopeBindings)if(existing.generationId!==binding.generationId&&existing.activation==="declaration"&&existing.dispatchCallId===void 0&&existing.workspaceIdentity===binding.workspaceIdentity&&existing.taskId===binding.taskId&&existing.ownerSessionId===binding.ownerSessionId)pendingScopeBindings.delete(existingKey),scopeBindingTombstones.set(existingKey,{...existing,revision:existing.revision+1,lifecycleState:"superseded",updatedAt:Date.now()})}if(!exact&&pendingScopeBindings.size>=MAX_PENDING_SCOPE_BINDINGS)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:`Scope binding capacity ${MAX_PENDING_SCOPE_BINDINGS} is exhausted; complete or expire a live task before retrying.`};let key=bindingKey(binding);return pendingScopeBindings.delete(key),pendingScopeBindings.set(key,binding),{ok:!0,binding}}function getScopeBindingForParentDispatch(input){if(sweepExpired(),!input.parentSessionId.trim()||!input.dispatchCallId.trim())return null;let active=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.parentCallId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);if(active.length>1)return null;if(active.length===1)return active[0];let pending=[...pendingScopeBindings.values()].filter((binding)=>binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.ownerMessageId===input.dispatchCallId&&binding.dispatchCallId===input.dispatchCallId);return pending.length===1?pending[0]:null}function createPrFeedbackScopeBinding(input){if(!input.ownerSessionId.trim()||!input.ownerMessageId.trim()||!input.workflowSessionId.trim()||!input.workflowRevisionDigest.trim()||!isStrictTaskId2(input.taskId))return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory),files=normalizeScopeFiles(input.files);if(!workspaceIdentity||!files)return null;let now=Date.now(),workflowIdentity=`pr-feedback:${input.workflowSessionId}`;return{version:2,bindingId:newIdentity(),generationId:newIdentity(),revision:1,lifecycleState:"live",workspaceIdentity,planId:workflowIdentity,planStructureHash:input.workflowRevisionDigest,taskId:input.taskId,ownerSessionId:input.ownerSessionId,ownerMessageId:input.ownerMessageId,dispatchCallId:input.dispatchCallId,activation:input.activation??(input.dispatchCallId?"pending_child":"declaration"),source:"pr_feedback",files,declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS,workflowSessionId:input.workflowSessionId,workflowRevisionDigest:input.workflowRevisionDigest}}function getAuthorizedPrFeedbackScopeBinding(input){sweepExpired();let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity||!input.activeSessionId.trim())return null;let matches=[...pendingScopeBindings.values()].filter((binding)=>binding.workspaceIdentity===workspaceIdentity&&binding.source==="pr_feedback"&&binding.activation==="active"&&binding.ownerSessionId===input.activeSessionId&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&typeof binding.workflowSessionId==="string"&&binding.workflowSessionId===binding.parentOwnerSessionId&&typeof binding.workflowRevisionDigest==="string"&&binding.workflowRevisionDigest.length>0&&binding.planId===`pr-feedback:${binding.workflowSessionId}`&&binding.planStructureHash===binding.workflowRevisionDigest);return matches.length===1?matches[0]:null}function describeScopeWorkspaceMismatch(input){if(sweepExpired(),!input.activeSessionId.trim())return null;let workspaceIdentity=canonicalWorkspaceIdentity(input.directory);if(!workspaceIdentity)return null;let first=[...pendingScopeBindings.values()].filter((binding)=>binding.ownerSessionId===input.activeSessionId&&binding.activation==="active"&&binding.source!=="pr_feedback"&&(!input.taskId||binding.taskId===input.taskId)&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId&&binding.workspaceIdentity!==workspaceIdentity)[0];if(!first)return null;return`SCOPE_WORKSPACE_MISMATCH: an active scope binding for session "${sanitizeDiagnosticText(input.activeSessionId)}" (task ${first.taskId}, source ${first.source}) is rooted at "${sanitizeDiagnosticText(first.workspaceIdentity)}", but this gate resolved "${sanitizeDiagnosticText(workspaceIdentity)}". The gate is using the wrong workspace root for this session.`}function clearScopeBindings(predicate){let removed=[];if(!predicate)return removed.push(...pendingScopeBindings.values()),pendingScopeBindings.clear(),scopeBindingTombstones.clear(),removed;for(let[key,binding]of pendingScopeBindings)if(predicate(binding))removed.push(binding),pendingScopeBindings.delete(key);return removed}function clearExactScopeBinding(input){let candidate=pendingScopeBindings.get(input.generationId);if(!candidate||candidate.bindingId!==input.bindingId)return null;return pendingScopeBindings.delete(input.generationId),candidate}function installScopeBindingTombstone(binding){pendingScopeBindings.delete(binding.generationId),scopeBindingTombstones.delete(binding.generationId),scopeBindingTombstones.set(binding.generationId,binding);while(scopeBindingTombstones.size>MAX_SCOPE_BINDING_TOMBSTONES){let oldest=scopeBindingTombstones.keys().next().value;if(!oldest)break;scopeBindingTombstones.delete(oldest)}}function hasScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live")}function hasDeliberateScopeBindingDenyOverlay(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);return Boolean(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.revision>=binding.revision&&tombstone.lifecycleState!=="live"&&tombstone.lifecycleState!=="expired")}function clearSweepTombstoneForRevival(binding){let tombstone=scopeBindingTombstones.get(binding.generationId);if(tombstone&&tombstone.bindingId===binding.bindingId&&tombstone.lifecycleState==="expired"&&tombstone.revision<=binding.revision)scopeBindingTombstones.delete(binding.generationId)}function installFailedRevocationOverlay(binding,reason){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||current.revision!==binding.revision)return!1;let now=Date.now();return installScopeBindingTombstone({...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)}),!0}function installScopeBindingRetirementIntent(binding){let source=pendingScopeBindings.get(binding.generationId)??(binding.version===2?binding:null);if(!source||source.bindingId!==binding.bindingId)return null;let now=Date.now(),tombstone={...source,revision:source.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(source.expiresAt,now)};return installScopeBindingTombstone(tombstone),tombstone}function updateExactScopeBinding(binding){let current=pendingScopeBindings.get(binding.generationId);if(!current||current.bindingId!==binding.bindingId||binding.revision<=current.revision)return{ok:!1,code:"SCOPE_BINDING_CAPACITY",message:"The exact binding generation is stale or no longer active."};return pendingScopeBindings.set(binding.generationId,binding),{ok:!0,binding}}function createClaimedScopeBinding(previous,input){let now=Date.now();return{...previous,generationId:newIdentity(),revision:1,ownerSessionId:input.childSessionId,childSessionId:input.childSessionId,ownerMessageId:input.dispatchCallId,dispatchCallId:input.dispatchCallId,parentOwnerSessionId:input.parentSessionId,parentCallId:input.dispatchCallId,activation:"active",predecessorGenerationId:previous.generationId,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function deriveChildScopeBinding(parent,input){let workspaceIdentity=canonicalWorkspaceIdentity(input.childDirectory);if(!workspaceIdentity||!input.childSessionId.trim()||!input.parentCallId.trim())throw Error("Cannot derive child scope binding without verified identity");let now=Date.now();return{...parent,generationId:newIdentity(),revision:1,workspaceIdentity,ownerSessionId:input.childSessionId,ownerMessageId:input.parentCallId,dispatchCallId:input.parentCallId,activation:"active",parentOwnerSessionId:parent.ownerSessionId,parentCallId:input.parentCallId,predecessorGenerationId:parent.generationId,childSessionId:input.childSessionId,source:"worktree_derived",declaredAt:now,updatedAt:now,leaseStartedAt:now,expiresAt:now+DEFAULT_SCOPE_BINDING_TTL_MS}}function scopeContains(scope,candidate){let flavor=getPathFlavor(),candidateIdentity=normalizePathIdentity(candidate,flavor).replace(/\\/g,"/");return scope.some((entry)=>{let entryIdentity=normalizePathIdentity(entry,flavor).replace(/\\/g,"/");return candidateIdentity===entryIdentity||candidateIdentity.startsWith(`${entryIdentity}/`)})}function isSubset(candidate,authority){return candidate.every((file2)=>scopeContains(authority,file2))}function resolveCoderScopeSources(input){let explicit=input.explicitFiles&&input.explicitFiles.length>0?normalizeScopeFiles(input.explicitFiles):null,plan=input.planFiles&&input.planFiles.length>0?normalizeScopeFiles(input.planFiles):null,directives=input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0?normalizeScopeFiles(input.fileDirectiveFiles):null;if(input.explicitFiles&&input.explicitFiles.length>0&&!explicit)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.planFiles&&input.planFiles.length>0&&!plan)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(input.fileDirectiveFiles&&input.fileDirectiveFiles.length>0&&!directives)return{ok:!1,code:"SCOPE_NOT_DECLARED",sources:{explicit,plan,directives}};if(explicit){let conflict=plan&&!isSubset(plan,explicit)?{source:"plan",files:plan}:directives&&!isSubset(directives,explicit)?{source:"file_directive",files:directives}:null;if(conflict)return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"declare_scope",authoritativeFiles:explicit,conflictingSource:conflict.source,conflictingFiles:conflict.files,disagreement:conflict.files.filter((file2)=>!scopeContains(explicit,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:explicit,source:"declare_scope"}}if(plan){if(directives&&!isSubset(directives,plan))return{ok:!1,code:"SCOPE_CONFLICT",authoritativeSource:"plan",authoritativeFiles:plan,conflictingSource:"file_directive",conflictingFiles:directives,disagreement:directives.filter((file2)=>!scopeContains(plan,file2)),sources:{explicit,plan,directives}};return{ok:!0,files:plan,source:"plan"}}if(directives)return{ok:!0,files:directives,source:"file_directive"};return{ok:!1,code:"SCOPE_NOT_DECLARED"}}function renderSet(values,max=8){if(!values)return"(none)";return`${values.slice(0,max).map((value)=>JSON.stringify(value)).join(", ")}${values.length>max?`, … +${values.length-max}`:""}`}function formatCoderScopeConflict(decision){if(decision.code!=="SCOPE_CONFLICT")return"SCOPE_NOT_DECLARED: coder delegation has no complete, valid, non-empty scope.";return`SCOPE_CONFLICT: ${decision.authoritativeSource} authority [${renderSet(decision.authoritativeFiles)}] does not cover ${decision.conflictingSource} [${renderSet(decision.conflictingFiles)}]; outside authority: [${renderSet(decision.disagreement)}]. Architect: reconcile save_plan(files_touched), FILE directives, or declare_scope, then dispatch a new Task call.`}var MAX_PENDING_SCOPE_BINDINGS=256,DEFAULT_SCOPE_BINDING_TTL_MS=3600000,MAX_SCOPE_BINDING_TOMBSTONES=256,pendingScopeBindings,scopeBindingTombstones,MAX_SCOPE_PATH_BYTES=4096,MAX_SCOPE_FILES_BYTES=1048576;var init_scope_binding=__esm(()=>{init_ledger();init_utils3();init_path_identity();pendingScopeBindings=new Map,scopeBindingTombstones=new Map});var exports_scope_persistence={};__export(exports_scope_persistence,{writeScopeToDisk:()=>writeScopeToDisk,writeScopeBindingToDisk:()=>writeScopeBindingToDisk,tombstoneScopeBinding:()=>tombstoneScopeBinding,resolveScopeWithFallbacks:()=>resolveScopeWithFallbacks,resolveScopeBindingFromDisk:()=>resolveScopeBindingFromDisk,resolveAuthorizedScopeBindingForSessionDetailed:()=>resolveAuthorizedScopeBindingForSessionDetailed,resolveAuthorizedScopeBindingForSession:()=>resolveAuthorizedScopeBindingForSession,resolveAuthorizedScopeBindingDetailed:()=>resolveAuthorizedScopeBindingDetailed,resolveAuthorizedScopeBinding:()=>resolveAuthorizedScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk:()=>resolveAuthorizedPrFeedbackScopeBindingFromDisk,replaceExistingScopeDeclaration:()=>replaceExistingScopeDeclaration,refreshScopeBindingLease:()=>refreshScopeBindingLease,readScopeFromDisk:()=>readScopeFromDisk,readScopeBindingFromDisk:()=>readScopeBindingFromDisk,readPlanScope:()=>readPlanScope,pruneScopeBindingTombstones:()=>pruneScopeBindingTombstones,persistAndRegisterScopeBinding:()=>persistAndRegisterScopeBinding,flushScopeBindingMaintenance:()=>flushScopeBindingMaintenance,clearScopeForTask:()=>clearScopeForTask,clearScopeBindingFromDisk:()=>clearScopeBindingFromDisk,clearAllScopes:()=>clearAllScopes,claimScopeBindingForChildDurably:()=>claimScopeBindingForChildDurably,_scopePersistenceInternals:()=>_scopePersistenceInternals});import{createHash as createHash11}from"node:crypto";import*as fs17 from"node:fs";import*as path24 from"node:path";function lockSyncWithBoundedRetry(targetPath,attempts=41){let lastError;for(let attempt=0;attempt<attempts;attempt++)try{return lockfileWithSync.lockSync(targetPath,{stale:LOCK_STALE_MS2,realpath:!1})}catch(error49){if(lastError=error49,attempt+1<attempts)Atomics.wait(syncLockWait,0,0,25)}throw lastError instanceof Error?lastError:Error("Lock unavailable")}function getScopesDir(directory){return path24.join(directory,SCOPES_DIR)}function normalizePathForComparison(value){let normalized=path24.resolve(value);return process.platform==="win32"?normalized.toLowerCase():normalized}function isSafeTaskId(taskId){if(typeof taskId!=="string")return!1;if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(taskId))return!1;let head=taskId.replace(/\.+$/,"").split(".")[0].toUpperCase();if(WINDOWS_RESERVED.has(head))return!1;return!0}function isScopesDirSafe(directory,scopesDir){try{let resolvedWorkspace=fs17.realpathSync(directory),expectedSwarmDir=path24.join(resolvedWorkspace,".swarm"),expectedScopesDir=path24.join(expectedSwarmDir,"scopes"),swarmStat=fs17.lstatSync(expectedSwarmDir),scopesStat=fs17.lstatSync(expectedScopesDir);if(!swarmStat.isDirectory()||swarmStat.isSymbolicLink()||!scopesStat.isDirectory()||scopesStat.isSymbolicLink())return!1;let resolvedScopes=fs17.realpathSync(scopesDir);if(normalizePathForComparison(resolvedScopes)!==normalizePathForComparison(expectedScopesDir))return!1;let rel=path24.relative(resolvedWorkspace,resolvedScopes);return rel.length>0&&!rel.startsWith("..")&&!path24.isAbsolute(rel)}catch{return!1}}function resolveSafeScopeFileForUnlink(directory,targetPath){try{let resolvedWorkspace=fs17.realpathSync(directory),scopesDir=path24.join(resolvedWorkspace,SCOPES_DIR);if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let candidate=path24.resolve(targetPath),resolvedCandidate=fs17.realpathSync(candidate);if(normalizePathForComparison(path24.dirname(candidate))!==normalizePathForComparison(scopesDir)||normalizePathForComparison(resolvedCandidate)!==normalizePathForComparison(candidate))return null;let relative7=path24.relative(resolvedWorkspace,resolvedCandidate);if(relative7.length===0||relative7===".."||relative7.startsWith(`..${path24.sep}`)||path24.isAbsolute(relative7))return null;let leafStat=fs17.lstatSync(candidate);if(!leafStat.isFile()||leafStat.isSymbolicLink())return null;if(!isScopesDirSafe(resolvedWorkspace,scopesDir))return null;let finalResolvedCandidate=fs17.realpathSync(candidate),finalLeafStat=fs17.lstatSync(candidate);if(normalizePathForComparison(finalResolvedCandidate)!==normalizePathForComparison(candidate)||!finalLeafStat.isFile()||finalLeafStat.isSymbolicLink()||finalLeafStat.dev!==leafStat.dev||finalLeafStat.ino!==leafStat.ino)return null;return candidate}catch{return null}}function getScopeFilePath(directory,taskId){if(!isSafeTaskId(taskId))throw Error(`Invalid taskId for scope persistence: ${taskId}`);return path24.join(getScopesDir(directory),`scope-${taskId}.json`)}function getLegacyBindingFilePath(directory,taskId,ownerSessionId){if(!isSafeTaskId(taskId)||!ownerSessionId.trim())throw Error("Invalid identity for scope binding persistence");let ownerHash=createHash11("sha256").update(ownerSessionId).digest("hex").slice(0,24);return path24.join(getScopesDir(directory),`binding-${taskId}-${ownerHash}.json`)}function getBindingFilePath(directory,binding){if(!isSafeTaskId(binding.taskId)||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId))throw Error("Invalid exact identity for scope binding persistence");return path24.join(getScopesDir(directory),`binding-${binding.taskId}-${binding.bindingId}-${binding.generationId}.json`)}function getGenerationLockPath(bindingPath){return`${bindingPath}.generation-lock`}function getRetirementIntentPath(bindingPath){return`${bindingPath}.retirement-intent`}function hasDurableRetirementIntent(bindingPath,binding){let raw=readBoundedFile(getRetirementIntentPath(bindingPath));if(!raw)return!1;try{let intent=JSON.parse(raw);return intent.bindingId===binding.bindingId&&intent.generationId===binding.generationId}catch{return!1}}function ensureLockTargetSync(targetPath){try{let scopesDir=path24.dirname(targetPath),swarmDir=path24.dirname(scopesDir);if(path24.basename(scopesDir)!=="scopes"||path24.basename(swarmDir)!==".swarm")return!1;assertProjectRoot(path24.dirname(swarmDir)),fs17.mkdirSync(path24.dirname(targetPath),{recursive:!0});let nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(targetPath,fs17.constants.O_WRONLY|fs17.constants.O_CREAT|nofollow);return fs17.closeSync(fd),!0}catch{return!1}}function exactBindingPrefix(taskId){return`binding-${taskId}-`}function readBoundedFile(filePath){let nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(filePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile()||stat5.size<=0||stat5.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat5.size);return fs17.readSync(fd,buffer,0,stat5.size,0),buffer.toString("utf8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}}function deterministicIdentity(value){let hex3=createHash11("sha256").update(value).digest("hex").slice(0,32);return`${hex3.slice(0,8)}-${hex3.slice(8,12)}-4${hex3.slice(13,16)}-a${hex3.slice(17,20)}-${hex3.slice(20)}`}function validateScopeBindingPayload(directory,parsed,options={}){let workspaceIdentity=canonicalWorkspaceIdentity(directory),files=Array.isArray(parsed.files)?normalizeScopeFiles(parsed.files.filter((file2)=>typeof file2==="string")):null;if(parsed.version!==2||!workspaceIdentity||parsed.workspaceIdentity!==workspaceIdentity||!isSafeTaskId(parsed.taskId??"")||!files||typeof parsed.planId!=="string"||!parsed.planId||typeof parsed.planStructureHash!=="string"||!parsed.planStructureHash||typeof parsed.ownerSessionId!=="string"||!parsed.ownerSessionId.trim()||typeof parsed.ownerMessageId!=="string"||!parsed.ownerMessageId.trim()||!["declaration","pending_child","active"].includes(parsed.activation??"")||!["declare_scope","plan","file_directive","pr_feedback","worktree_derived"].includes(parsed.source??"")||typeof parsed.declaredAt!=="number"||!Number.isFinite(parsed.declaredAt)||typeof parsed.expiresAt!=="number"||!Number.isFinite(parsed.expiresAt))return null;let legacySeed=JSON.stringify({workspaceIdentity,planId:parsed.planId,planStructureHash:parsed.planStructureHash,taskId:parsed.taskId,ownerSessionId:parsed.ownerSessionId,ownerMessageId:parsed.ownerMessageId,dispatchCallId:parsed.dispatchCallId,activation:parsed.activation,source:parsed.source,files,declaredAt:parsed.declaredAt}),bindingId=isScopeBindingIdentity(parsed.bindingId)?parsed.bindingId:options.allowLegacy?deterministicIdentity(`binding\x00${legacySeed}`):null,generationId=isScopeBindingIdentity(parsed.generationId)?parsed.generationId:options.allowLegacy?deterministicIdentity(`generation\x00${legacySeed}`):null;if(!bindingId||!generationId)return null;let lifecycleState=parsed.lifecycleState??(options.allowLegacy?"live":void 0);if(!lifecycleState||!["live","expired","revoked","superseded"].includes(lifecycleState))return null;let revision=parsed.revision??(options.allowLegacy?1:void 0);if(!Number.isSafeInteger(revision)||(revision??0)<1)return null;let updatedAt=parsed.updatedAt??parsed.declaredAt,leaseStartedAt=parsed.leaseStartedAt??parsed.declaredAt;if(typeof updatedAt!=="number"||typeof leaseStartedAt!=="number")return null;let now=Date.now();if(parsed.declaredAt>now||updatedAt<parsed.declaredAt||leaseStartedAt<parsed.declaredAt||parsed.activation==="declaration"&&parsed.dispatchCallId!==void 0||parsed.activation==="pending_child"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId)||parsed.activation==="active"&&(typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId||typeof parsed.parentOwnerSessionId!=="string"||!parsed.parentOwnerSessionId||parsed.ownerSessionId===parsed.parentOwnerSessionId||parsed.parentCallId!==parsed.dispatchCallId))return null;return{...parsed,bindingId,generationId,revision,lifecycleState,files,workspaceIdentity,updatedAt,leaseStartedAt}}function exactFilenameMatches(filePath,binding){return normalizePathForComparison(filePath)===normalizePathForComparison(getBindingFilePath(binding.workspaceIdentity,binding))}function migrateLegacyBindingsSync(directory,scanCapacity=bindingFileScanCapacity){try{assertProjectRoot(directory)}catch{return!1}let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return!1;let names;try{names=fs17.readdirSync(scopesDir).sort()}catch{return!0}if(names.length>scanCapacity)return!1;for(let name of names){let match=/^binding-(.+)-([a-f0-9]{24})\.json$/i.exec(name);if(!match||!isSafeTaskId(match[1]))continue;let legacyPath=path24.join(scopesDir,name),releaseMigration;try{releaseMigration=lockfileWithSync.lockSync(legacyPath,{stale:LOCK_STALE_MS2,realpath:!1})}catch{return!1}try{let raw=readBoundedFile(legacyPath),binding=null;try{binding=raw?validateScopeBindingPayload(directory,JSON.parse(raw),{allowLegacy:!0}):null}catch{binding=null}let ownerHash=binding?createHash11("sha256").update(binding.ownerSessionId).digest("hex").slice(0,24):"",valid=binding&&binding.taskId===match[1]&&ownerHash.toLowerCase()===match[2].toLowerCase()&&normalizePathForComparison(getLegacyBindingFilePath(directory,binding.taskId,binding.ownerSessionId))===normalizePathForComparison(legacyPath),archiveDir=path24.join(scopesDir,"archive");fs17.mkdirSync(archiveDir,{recursive:!0});let archiveStat=fs17.lstatSync(archiveDir);if(!archiveStat.isDirectory()||archiveStat.isSymbolicLink())return!1;let archiveDigest=createHash11("sha256").update(raw??name).digest("hex").slice(0,32);if(valid&&binding){let exactPath=getBindingFilePath(directory,binding);if(!fs17.existsSync(exactPath))atomicWriteSwarmFileSync(exactPath,JSON.stringify(binding,null,2));else{let existingRaw=readBoundedFile(exactPath),existing=existingRaw?validateScopeBindingPayload(directory,JSON.parse(existingRaw)):null;if(!existing||existing.bindingId!==binding.bindingId||existing.generationId!==binding.generationId)return!1}}let archivePath=path24.join(archiveDir,`${valid?"migrated":"quarantined"}-${archiveDigest}.json`);if(!fs17.existsSync(archivePath))fs17.renameSync(legacyPath,archivePath);else fs17.unlinkSync(legacyPath);fs17.writeFileSync(`${archivePath}.receipt.json`,JSON.stringify({version:1,legacyName:name,result:valid?"migrated":"quarantined",bindingId:binding?.bindingId,generationId:binding?.generationId},null,2));let archiveEntries=fs17.readdirSync(archiveDir).sort();for(let stale of archiveEntries.slice(0,Math.max(0,archiveEntries.length-2*MAX_DURABLE_TOMBSTONES))){let stalePath=path24.join(archiveDir,stale);try{let stat5=fs17.lstatSync(stalePath);if(stat5.isFile()&&!stat5.isSymbolicLink())fs17.unlinkSync(stalePath)}catch{}}}catch{return!1}finally{try{releaseMigration?.()}catch{}}}return!0}async function writeScopeToDisk(directory,taskId,files,ttlMs=DEFAULT_TTL_MS){if(!isSafeTaskId(taskId))return;if(!Array.isArray(files)||files.length===0)return;if(files.length>MAX_FILES_PER_SCOPE)return;try{assertProjectRoot(directory)}catch{return}let scopesDir=getScopesDir(directory),scopePath=getScopeFilePath(directory,taskId);try{fs17.mkdirSync(scopesDir,{recursive:!0})}catch{return}if(!isScopesDirSafe(directory,scopesDir))return;let now=Date.now(),payload={version:SCOPE_SCHEMA_VERSION,taskId,declaredAt:now,expiresAt:now+ttlMs,files:[...files]},content=JSON.stringify(payload,null,2);try{let flags=fs17.constants.O_WRONLY|fs17.constants.O_CREAT,nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(scopePath,flags|nofollow);fs17.closeSync(fd)}catch{return}let release;try{let lockPath=getGenerationLockPath(scopePath);if(!await ensureLockTarget(lockPath))return;release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),await atomicWrite(scopePath,content)}catch{}finally{if(release)try{await release()}catch{}}}async function writeScopeBindingToDisk(directory,binding){try{assertProjectRoot(directory)}catch(error49){return persistenceFailure(`Scope persistence project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}if(!isSafeTaskId(binding.taskId)||binding.version!==2)return persistenceFailure("Invalid binding schema or task identity.");let workspaceIdentity=canonicalWorkspaceIdentity(directory),files=normalizeScopeFiles(binding.files);if(!workspaceIdentity||workspaceIdentity!==binding.workspaceIdentity||!files||!binding.ownerSessionId||!binding.ownerMessageId||!isScopeBindingIdentity(binding.bindingId)||!isScopeBindingIdentity(binding.generationId)||binding.revision<1||binding.lifecycleState==="live"&&binding.expiresAt<=Date.now())return persistenceFailure("Binding identity, workspace, scope, or lease is invalid.");let scopesDir=getScopesDir(directory),scopePath=getBindingFilePath(directory,binding);try{fs17.mkdirSync(scopesDir,{recursive:!0})}catch{return persistenceFailure("Could not create the durable scope store.")}if(!isScopesDirSafe(directory,scopesDir))return persistenceFailure("The durable scope store failed containment checks.");let content=JSON.stringify({...binding,files},null,2);try{let flags=fs17.constants.O_WRONLY|fs17.constants.O_CREAT,nofollow=fs17.constants.O_NOFOLLOW??0,fd=fs17.openSync(scopePath,flags|nofollow);fs17.closeSync(fd)}catch{return persistenceFailure("Could not create the exact generation record.")}let release;try{let lockPath=getGenerationLockPath(scopePath);if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare exact generation lock.");release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),await atomicWrite(scopePath,content);let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(directory,JSON.parse(verifiedRaw)):null;if(!verified||verified.bindingId!==binding.bindingId||verified.generationId!==binding.generationId||verified.revision!==binding.revision)return persistenceFailure("Exact generation verification failed after write.");return{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Exact generation write failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function persistenceFailure(message){return{ok:!1,code:"SCOPE_BINDING_PERSISTENCE_FAILED",message}}async function persistAndRegisterScopeBinding(directory,binding){let persisted=await writeScopeBindingToDisk(directory,binding);if(!persisted.ok)return persisted;let admission=registerScopeBinding(persisted.value);if(admission.ok)return scheduleScopeBindingMaintenance(directory),{ok:!0,value:persisted.value};let rollback=await tombstoneScopeBinding(directory,persisted.value,"superseded");return{ok:!1,code:rollback.ok?admission.code:"SCOPE_BINDING_PERSISTENCE_FAILED",message:rollback.ok?admission.message:`Memory admission failed and rollback failed: ${rollback.message}`}}function readScopeBindingFromDisk(input){let resolved=resolveScopeBindingFromDisk({...input,includeExpired:!1});return resolved.status==="found"?resolved.binding:null}function resolveScopeBindingFromDisk(input){if(!isSafeTaskId(input.taskId))return{status:"not_declared"};let completeSet=readAllExactBindings(input.directory);if(!completeSet)return scheduleScopeBindingMaintenance(input.directory),{status:"overloaded"};let candidates=completeSet.filter((parsed)=>parsed.taskId===input.taskId&&parsed.planId===derivePlanId(input.plan)&&parsed.planStructureHash===computePlanStructureHash(input.plan)&&parsed.ownerSessionId===input.ownerSessionId&&(input.requireDispatchCorrelation!==!0||isDispatchCorrelated(parsed))&&(input.requireDeclaration!==!0||parsed.activation==="declaration"&&parsed.dispatchCallId===void 0)&&(input.parentCallId===void 0||parsed.parentCallId===input.parentCallId)),live=candidates.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now());if(live.length>1)return{status:"ambiguous",candidates:live.slice(0,8),totalCandidates:live.length};if(live.length===1)return{status:"found",binding:live[0]};let expired=candidates.filter((candidate)=>candidate.lifecycleState!=="live"||candidate.expiresAt<=Date.now());return input.includeExpired&&expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expired.length}:{status:"not_declared"}}function isDispatchCorrelated(binding){return binding.activation==="active"&&typeof binding.dispatchCallId==="string"&&binding.dispatchCallId.length>0&&binding.ownerMessageId===binding.dispatchCallId&&typeof binding.parentOwnerSessionId==="string"&&binding.parentOwnerSessionId.length>0&&binding.ownerSessionId!==binding.parentOwnerSessionId&&binding.parentCallId===binding.dispatchCallId}function clearScopeBindingFromDisk(input){let localRetirement=installScopeBindingRetirementIntent(input.binding);try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope retirement project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let release;try{let resolvedWorkspace=fs17.realpathSync(input.directory),scopePath=getBindingFilePath(resolvedWorkspace,input.binding);if(!isScopesDirSafe(resolvedWorkspace,getScopesDir(resolvedWorkspace)))return persistenceFailure("The durable scope store failed containment checks.");let retirementIntentPath=getRetirementIntentPath(scopePath);atomicWriteSync(retirementIntentPath,JSON.stringify({version:1,bindingId:input.binding.bindingId,generationId:input.binding.generationId,createdAt:Date.now()})),scheduleScopeBindingMaintenance(resolvedWorkspace);let lockPath=getGenerationLockPath(scopePath);if(!ensureLockTargetSync(lockPath))return persistenceFailure("Could not prepare exact retirement lock.");release=lockSyncWithBoundedRetry(lockPath);let raw=readBoundedFile(scopePath);if(!raw){try{fs17.unlinkSync(retirementIntentPath)}catch{}return localRetirement?{ok:!0,value:localRetirement}:persistenceFailure("Exact generation disappeared before serialized retirement.")}let current=validateScopeBindingPayload(resolvedWorkspace,JSON.parse(raw));if(!current||current.bindingId!==input.binding.bindingId||current.generationId!==input.binding.generationId)return persistenceFailure("Exact generation identity changed before serialized retirement.");if(current.lifecycleState!=="live"){installScopeBindingTombstone(current);try{fs17.unlinkSync(retirementIntentPath)}catch{}return{ok:!0,value:current}}let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:"revoked",updatedAt:now,expiresAt:Math.min(current.expiresAt,now)};atomicWriteSync(scopePath,JSON.stringify(tombstone,null,2));let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(resolvedWorkspace,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==tombstone.revision||verified.lifecycleState!=="revoked")return persistenceFailure("Serialized retirement verification failed.");installScopeBindingTombstone(verified);try{fs17.unlinkSync(retirementIntentPath)}catch{}return scheduleScopeBindingMaintenance(resolvedWorkspace),{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Serialized retirement failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{try{release?.()}catch{}}}async function tombstoneScopeBinding(directory,binding,reason){let currentPath=getBindingFilePath(directory,binding),generationLockPath=getGenerationLockPath(currentPath);if(!await ensureLockTarget(generationLockPath))return installFailedRevocationOverlay(binding,reason),persistenceFailure("Could not prepare exact generation lock.");let release;try{release=await import_proper_lockfile3.default.lock(generationLockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1});let raw=readBoundedFile(currentPath);if(!raw)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Exact generation disappeared before tombstone.");let current=validateScopeBindingPayload(directory,JSON.parse(raw));if(!current||current.bindingId!==binding.bindingId||current.generationId!==binding.generationId)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Exact generation identity changed before tombstone.");if(current.revision!==binding.revision)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Tombstone CAS revision is stale."};if(current.lifecycleState!=="live")return{ok:!0,value:current};let now=Date.now(),tombstone={...current,revision:current.revision+1,lifecycleState:reason,updatedAt:now,expiresAt:Math.min(current.expiresAt,now)};await atomicWrite(currentPath,JSON.stringify(tombstone,null,2));let verifiedRaw=readBoundedFile(currentPath),verified=verifiedRaw?validateScopeBindingPayload(directory,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==tombstone.revision||verified.lifecycleState!==reason)return installFailedRevocationOverlay(binding,reason),persistenceFailure("Tombstone verification failed.");return clearExactScopeBinding(binding),installScopeBindingTombstone(verified),scheduleScopeBindingMaintenance(directory),{ok:!0,value:verified}}catch(error49){return installFailedRevocationOverlay(binding,reason),persistenceFailure(`Tombstone failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}async function ensureLockTarget(targetPath){return ensureLockTargetSync(targetPath)}async function refreshScopeBindingLease(input){let scopePath;try{scopePath=getBindingFilePath(input.directory,input)}catch{return persistenceFailure("Invalid refresh identity.")}let generationLockPath=getGenerationLockPath(scopePath),createdGenerationLockTarget=!fs17.existsSync(generationLockPath);if(!await ensureLockTarget(generationLockPath))return persistenceFailure("Could not prepare refresh lock.");let release;try{if(release=await import_proper_lockfile3.default.lock(generationLockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1}),hasDurableRetirementIntent(scopePath,input))return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Refresh cannot renew a generation with durable retirement intent."};let raw=readBoundedFile(scopePath),current=raw?validateScopeBindingPayload(input.directory,JSON.parse(raw)):null;if(!current||current.bindingId!==input.bindingId||current.generationId!==input.generationId||current.taskId!==input.taskId||current.ownerSessionId!==input.activeSessionId)return{ok:!1,code:"SCOPE_BINDING_STALE",message:"Refresh identity is not the exact current session/task generation."};if(current.lifecycleState!=="live"||current.expiresAt<=Date.now()||current.revision!==input.expectedRevision)return{ok:!1,code:current.expiresAt<=Date.now()?"SCOPE_BINDING_EXPIRED":"SCOPE_BINDING_STALE",message:"Refresh cannot renew an expired, tombstoned, or stale generation."};let now=Date.now(),refreshed={...current,revision:current.revision+1,updatedAt:now,leaseStartedAt:now,expiresAt:now+Math.max(1,input.ttlMs??DEFAULT_SCOPE_BINDING_TTL_MS)};await atomicWrite(scopePath,JSON.stringify(refreshed,null,2));let verifyRaw=readBoundedFile(scopePath),verified=verifyRaw?validateScopeBindingPayload(input.directory,JSON.parse(verifyRaw)):null;if(!verified||verified.revision!==refreshed.revision||verified.expiresAt!==refreshed.expiresAt)return persistenceFailure("Refreshed lease verification failed.");return updateExactScopeBinding(verified),{ok:!0,value:verified}}catch(error49){return persistenceFailure(`Lease refresh failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}if(createdGenerationLockTarget&&!fs17.existsSync(scopePath))try{fs17.unlinkSync(generationLockPath)}catch{}}}function claimBaseName(binding){return`claim-${createHash11("sha256").update(`${binding.bindingId}\x00${binding.generationId}\x00${binding.dispatchCallId??""}`).digest("hex").slice(0,40)}`}function readAllExactBindings(directory,options={}){let scopesDir=getScopesDir(directory);try{fs17.lstatSync(scopesDir)}catch(error49){return error49.code==="ENOENT"?[]:null}if(!isScopesDirSafe(directory,scopesDir))return null;let scanCapacity=options.maintenanceScan?maintenanceFileScanCapacity:bindingFileScanCapacity;if(!migrateLegacyBindingsSync(directory,scanCapacity))return null;let names;try{names=fs17.readdirSync(scopesDir).sort()}catch{return[]}if(names.length>scanCapacity)return null;let bindings=[];for(let name of names){if(!name.startsWith("binding-")||!name.endsWith(".json"))continue;let filePath=path24.join(scopesDir,name),raw=readBoundedFile(filePath);if(!raw)continue;try{let binding=validateScopeBindingPayload(directory,JSON.parse(raw));if(binding&&exactFilenameMatches(filePath,binding))if(hasDurableRetirementIntent(filePath,binding)){let createdAt=Date.now();try{let rawIntent=readBoundedFile(getRetirementIntentPath(filePath)),parsedIntent=rawIntent?JSON.parse(rawIntent):null;if(typeof parsedIntent?.createdAt==="number")createdAt=parsedIntent.createdAt}catch{}bindings.push({...binding,lifecycleState:"revoked",updatedAt:createdAt,expiresAt:Math.min(binding.expiresAt,createdAt)})}else bindings.push(binding)}catch{}}let liveCount=bindings.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()).length;if(options.enforceLiveCapacity!==!1&&liveCount>liveBindingCapacity)return null;return bindings}async function claimScopeBindingForChildDurably(input){if(!input.parentSessionId.trim()||!input.childSessionId.trim()||!input.dispatchCallId.trim()||input.parentSessionId===input.childSessionId)return persistenceFailure("Claim requires distinct non-empty parent/child identities and an exact dispatch call.");let initial=readAllExactBindings(input.directory);if(!initial)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The complete durable binding set could not be evaluated."};let pending=initial.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="pending_child"&&binding.ownerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.ownerMessageId===input.dispatchCallId);if(pending.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple pending generations match this exact Task dispatch."};let predecessor=pending[0];if(!predecessor){let successors=initial.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now()&&binding.activation==="active"&&binding.parentOwnerSessionId===input.parentSessionId&&binding.dispatchCallId===input.dispatchCallId&&binding.predecessorGenerationId);if(successors.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Multiple active successors match this Task dispatch."};let existing=successors[0];if(existing?.ownerSessionId===input.childSessionId){let admission=registerScopeBinding(existing);return admission.ok?{ok:!0,value:{previous:existing,claimed:existing}}:{ok:!1,code:admission.code,message:admission.message}}return existing?{ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This Task dispatch was already claimed by a different child session."}:initial.some((candidate)=>candidate.ownerSessionId===input.parentSessionId&&candidate.dispatchCallId===input.dispatchCallId)?{ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"No live pending generation remains for this Task dispatch."}:{ok:!1,code:"SCOPE_NOT_DECLARED",message:"No pending generation matches this Task dispatch."}}let claimPath=path24.join(getScopesDir(input.directory),`${claimBaseName(predecessor)}.json`);if(!await ensureLockTarget(claimPath))return persistenceFailure("Could not prepare the stable predecessor claim lock.");let release;try{release=await import_proper_lockfile3.default.lock(claimPath,{stale:LOCK_STALE_MS2,retries:{retries:5,minTimeout:50,maxTimeout:250},realpath:!1});let currentSet=readAllExactBindings(input.directory);if(!currentSet)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set became incomplete during claim."};let currentPredecessor=currentSet.find((binding)=>binding.generationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId),allSuccessors=currentSet.filter((binding)=>binding.predecessorGenerationId===predecessor.generationId&&binding.bindingId===predecessor.bindingId),successors=allSuccessors.filter((binding)=>binding.lifecycleState==="live"&&binding.expiresAt>Date.now());if(successors.length>1)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Incompatible successors exist for one predecessor generation."};let receiptRaw=readBoundedFile(claimPath),receipt=null;if(receiptRaw)try{let parsed=JSON.parse(receiptRaw);if(parsed.version!==1||parsed.predecessorGenerationId!==predecessor.generationId||!isScopeBindingIdentity(parsed.winnerGenerationId)||typeof parsed.childSessionId!=="string"||parsed.dispatchCallId!==input.dispatchCallId)return persistenceFailure("Claim winner receipt is malformed or belongs to another predecessor.");receipt=parsed}catch{return persistenceFailure("Claim winner receipt is malformed.")}if(receipt){let receiptWinner=allSuccessors.find((candidate)=>candidate.generationId===receipt?.winnerGenerationId);if(!receiptWinner)return persistenceFailure("Claim receipt has no verified successor; pending remains fail-closed for restart reconciliation.");if(receiptWinner.lifecycleState!=="live"||receiptWinner.expiresAt<=Date.now())fs17.writeFileSync(claimPath,""),receipt=null}if(receipt&&successors[0]&&receipt.winnerGenerationId!==successors[0].generationId)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"Claim receipt and durable successor disagree."};let existing=successors[0];if(existing){if(existing.ownerSessionId!==input.childSessionId)return{ok:!1,code:"SCOPE_BINDING_ALREADY_CLAIMED",message:"This pending generation has a winner in another child session."};if(await writeClaimReceipt(claimPath,predecessor,existing,input),currentPredecessor?.lifecycleState==="live")await tombstoneScopeBinding(input.directory,currentPredecessor,"superseded");let admission2=registerScopeBinding(existing);return admission2.ok?{ok:!0,value:{previous:predecessor,claimed:existing}}:{ok:!1,code:admission2.code,message:admission2.message}}if(!currentPredecessor||currentPredecessor.lifecycleState!=="live"||currentPredecessor.expiresAt<=Date.now())return{ok:!1,code:"SCOPE_BINDING_EXPIRED",message:"The pending predecessor expired before claim."};predecessor=currentPredecessor;let claimed=createClaimedScopeBinding(predecessor,input),persisted=await writeScopeBindingToDisk(input.directory,claimed);if(!persisted.ok)return persisted;let receiptWrite=await writeClaimReceipt(claimPath,predecessor,persisted.value,input);if(!receiptWrite.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),receiptWrite;let admission=registerScopeBinding(persisted.value);if(!admission.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),{ok:!1,code:admission.code,message:admission.message};let retired=await tombstoneScopeBinding(input.directory,predecessor,"superseded");if(!retired.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),persistenceFailure(`Successor was persisted but predecessor retirement failed: ${retired.message}`);return{ok:!0,value:{previous:predecessor,claimed:persisted.value}}}catch(error49){return persistenceFailure(`Claim transaction failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}async function writeClaimReceipt(claimPath,previous,claimed,input){let receipt={version:1,predecessorGenerationId:previous.generationId,winnerGenerationId:claimed.generationId,childSessionId:input.childSessionId,dispatchCallId:input.dispatchCallId,createdAt:Date.now()};try{await atomicWrite(claimPath,JSON.stringify(receipt,null,2));let raw=readBoundedFile(claimPath),verified=raw?JSON.parse(raw):null;return verified?.winnerGenerationId===receipt.winnerGenerationId&&verified.childSessionId===receipt.childSessionId?{ok:!0,value:verified}:persistenceFailure("Claim winner receipt verification failed.")}catch(error49){return persistenceFailure(`Claim winner receipt write failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}}async function replaceExistingScopeDeclaration(input){try{assertProjectRoot(input.directory)}catch(error49){return persistenceFailure(`Scope declaration project-root validation failed: ${error49 instanceof Error?error49.message:"unknown validation error"}`)}let{binding}=input;if(binding.activation!=="declaration"||binding.dispatchCallId!==void 0)return persistenceFailure("declare_scope may persist only a declaration generation.");let digest2=createHash11("sha256").update(`${binding.workspaceIdentity}\x00${binding.taskId}\x00${binding.ownerSessionId}`).digest("hex").slice(0,40),lockPath=path24.join(getScopesDir(input.directory),`declaration-${digest2}.lock-target`);if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare declaration transaction lock.");let release;try{release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:5,minTimeout:50,maxTimeout:250},realpath:!1});let all=readAllExactBindings(input.directory);if(!all)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set cannot be completely evaluated."};let owned=all.filter((candidate)=>candidate.lifecycleState==="live"&&candidate.expiresAt>Date.now()&&candidate.workspaceIdentity===binding.workspaceIdentity&&candidate.taskId===binding.taskId&&candidate.ownerSessionId===binding.ownerSessionId&&candidate.generationId!==binding.generationId);if(owned.length>0&&!input.replaceExisting)return{ok:!1,code:"SCOPE_BINDING_AMBIGUOUS",message:"A live owned generation already exists; retry declare_scope with replace_existing=true to revoke it atomically."};let persisted=await writeScopeBindingToDisk(input.directory,binding);if(!persisted.ok)return persisted;for(let prior of owned){let retired=await tombstoneScopeBinding(input.directory,prior,"superseded");if(!retired.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),persistenceFailure(`Replacement could not retire generation ${prior.generationId}: ${retired.message}`)}let admission=registerScopeBinding(persisted.value);if(!admission.ok)return await tombstoneScopeBinding(input.directory,persisted.value,"revoked"),{ok:!1,code:admission.code,message:admission.message};return{ok:!0,value:persisted.value}}catch(error49){return persistenceFailure(`Declaration transaction failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function scheduleScopeBindingMaintenance(directory){let key=normalizePathForComparison(directory);if(maintenanceJobs.has(key))return;while(maintenanceJobs.size>=MAX_MAINTENANCE_JOBS){let oldest=maintenanceJobs.keys().next().value;if(!oldest)break;maintenanceJobs.delete(oldest)}let job=Promise.resolve().then(()=>pruneScopeBindingTombstones(directory)).then(()=>{return}).catch(()=>{return}).finally(()=>maintenanceJobs.delete(key));maintenanceJobs.set(key,job)}async function flushScopeBindingMaintenance(directory){let key=directory?normalizePathForComparison(directory):void 0,job=key?maintenanceJobs.get(key):void 0;await Promise.all(job?[job]:[...maintenanceJobs.values()])}async function pruneScopeBindingTombstones(directory){let lockPath=path24.join(getScopesDir(directory),"maintenance.lock-target");if(!await ensureLockTarget(lockPath))return persistenceFailure("Could not prepare scope maintenance lock.");let release;try{release=await import_proper_lockfile3.default.lock(lockPath,{stale:LOCK_STALE_MS2,retries:{retries:3,minTimeout:50,maxTimeout:200},realpath:!1});let all=readAllExactBindings(directory,{enforceLiveCapacity:!1,maintenanceScan:!0});if(!all)return{ok:!1,code:"SCOPE_BINDING_STORE_OVERLOADED",message:"The durable binding set cannot be completely evaluated."};for(let binding of all){let filePath=getBindingFilePath(directory,binding);if(!hasDurableRetirementIntent(filePath,binding))continue;if((await tombstoneScopeBinding(directory,binding,"revoked")).ok)try{fs17.unlinkSync(getRetirementIntentPath(filePath))}catch{}}if(all=readAllExactBindings(directory,{enforceLiveCapacity:!1,maintenanceScan:!0}),!all)return persistenceFailure("The durable binding set changed during maintenance reconciliation.");let tombstones=all.filter((binding)=>binding.lifecycleState!=="live").sort((left,right)=>left.updatedAt-right.updatedAt),now=Date.now(),removable=tombstones.filter((binding,index)=>now-binding.updatedAt>MAX_TOMBSTONE_AGE_MS||index<tombstones.length-MAX_DURABLE_TOMBSTONES),removed=0;for(let binding of removable){let filePath=resolveSafeScopeFileForUnlink(directory,getBindingFilePath(directory,binding));if(!filePath)continue;let exactLockPath=getGenerationLockPath(filePath);if(!await ensureLockTarget(exactLockPath))continue;let releaseExact,removedExact=!1;try{releaseExact=await import_proper_lockfile3.default.lock(exactLockPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let latestRaw=readBoundedFile(filePath),latest=latestRaw?validateScopeBindingPayload(directory,JSON.parse(latestRaw)):null;if(!latest||latest.generationId!==binding.generationId||latest.revision!==binding.revision||latest.lifecycleState==="live"&&!hasDurableRetirementIntent(filePath,latest))continue;fs17.unlinkSync(filePath),removedExact=!0,removed++}catch{}finally{if(releaseExact)try{await releaseExact()}catch{}}if(removedExact&&!fs17.existsSync(filePath)){try{fs17.unlinkSync(exactLockPath)}catch{}try{fs17.unlinkSync(getRetirementIntentPath(filePath))}catch{}}}let receiptNames=[];try{receiptNames=fs17.readdirSync(getScopesDir(directory)).filter((name)=>/^claim-[a-f0-9]{40}\.json$/i.test(name)).slice(0,MAX_BINDING_FILES_TO_SCAN)}catch{}for(let name of receiptNames){let receiptPath=path24.join(getScopesDir(directory),name),releaseReceipt;try{releaseReceipt=await import_proper_lockfile3.default.lock(receiptPath,{stale:LOCK_STALE_MS2,retries:{retries:0},realpath:!1});let raw=readBoundedFile(receiptPath);if(!raw)continue;let receipt=null;try{receipt=JSON.parse(raw)}catch{}let winner=receipt?all.find((binding)=>binding.generationId===receipt?.winnerGenerationId):void 0;if(Date.now()-fs17.statSync(receiptPath).mtimeMs>MAX_TOMBSTONE_AGE_MS||Boolean(winner&&(winner.lifecycleState!=="live"||winner.expiresAt<=Date.now())))fs17.unlinkSync(receiptPath),removed++}catch{}finally{if(releaseReceipt)try{await releaseReceipt()}catch{}}}return{ok:!0,value:removed}}catch(error49){return persistenceFailure(`Scope maintenance failed: ${error49 instanceof Error?error49.message:"unknown I/O error"}`)}finally{if(release)try{await release()}catch{}}}function readCurrentPlan(directory){try{let planPath=path24.join(directory,".swarm","plan.json"),stat5=fs17.statSync(planPath);if(!stat5.isFile()||stat5.size>MAX_PLAN_BYTES)return null;let parsed=PlanSchema.safeParse(JSON.parse(fs17.readFileSync(planPath,"utf8")));return parsed.success?parsed.data:null}catch{return null}}function appendScopeBindingRevivalEvent(workspace,revived){try{appendCoreEventSync(workspace,{type:"scope_binding_auto_recovered",timestamp:new Date().toISOString(),taskId:revived.taskId,sessionId:revived.ownerSessionId,generationId:revived.generationId,revision:revived.revision,expiresAt:new Date(revived.expiresAt).toISOString()})}catch{}}function attemptIdleScopeBindingRevival(directory,resolution){if(resolution.status!=="expired")return null;if(resolution.totalCandidates!==1||resolution.candidates.length!==1)return null;let candidate=resolution.candidates[0];if(!candidate)return null;let now=Date.now();if(candidate.lifecycleState!=="live")return null;if(candidate.expiresAt>now)return null;if(now-candidate.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;if(hasDeliberateScopeBindingDenyOverlay(candidate))return null;let release;try{let resolvedWorkspace=fs17.realpathSync(directory);assertProjectRoot(resolvedWorkspace);let scopePath=getBindingFilePath(resolvedWorkspace,candidate);if(!isScopesDirSafe(resolvedWorkspace,getScopesDir(resolvedWorkspace)))return null;let lockPath=getGenerationLockPath(scopePath);if(!ensureLockTargetSync(lockPath))return null;release=lockSyncWithBoundedRetry(lockPath);let raw=readBoundedFile(scopePath);if(!raw)return null;let current=validateScopeBindingPayload(resolvedWorkspace,JSON.parse(raw));if(!current||current.bindingId!==candidate.bindingId||current.generationId!==candidate.generationId||current.revision!==candidate.revision||current.lifecycleState!=="live"||current.expiresAt>Date.now()||Date.now()-current.expiresAt>SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS)return null;let revivedAt=Date.now(),revived={...current,revision:current.revision+1,updatedAt:revivedAt,leaseStartedAt:revivedAt,expiresAt:revivedAt+DEFAULT_SCOPE_BINDING_TTL_MS};atomicWriteSync(scopePath,JSON.stringify(revived,null,2));let verifiedRaw=readBoundedFile(scopePath),verified=verifiedRaw?validateScopeBindingPayload(resolvedWorkspace,JSON.parse(verifiedRaw)):null;if(!verified||verified.revision!==revived.revision||verified.lifecycleState!=="live"||verified.expiresAt!==revived.expiresAt)return null;return clearSweepTombstoneForRevival(revived),appendScopeBindingRevivalEvent(resolvedWorkspace,revived),revived}catch{return null}finally{if(release)try{release()}catch{}}}function resolveAuthorizedScopeBindingForPlan(input){let resolution=resolveAuthorizedScopeBindingForPlanDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForPlanDetailed(input){let durable=resolveScopeBindingFromDisk({directory:input.directory,taskId:input.taskId,plan:input.plan,ownerSessionId:input.activeSessionId,requireDispatchCorrelation:!0,includeExpired:!0});if(durable.status==="found"){if(hasScopeBindingDenyOverlay(durable.binding))return{status:"expired",candidates:[durable.binding],totalCandidates:1};return registerScopeBinding(durable.binding).ok?durable:{status:"overloaded"}}if(durable.status==="expired"){let revived=attemptIdleScopeBindingRevival(input.directory,durable);if(revived){if(registerScopeBinding(revived).ok)return{status:"found",binding:revived}}}if(durable.status!=="not_declared")return durable;return{status:"not_declared"}}function resolveAuthorizedScopeBinding(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlan({...input,plan}):null}function resolveAuthorizedScopeBindingDetailed(input){let plan=readCurrentPlan(input.directory);return plan?resolveAuthorizedScopeBindingForPlanDetailed({...input,plan}):{status:"not_declared"}}function resolveAuthorizedScopeBindingForSession(input){let resolution=resolveAuthorizedScopeBindingForSessionDetailed(input);return resolution.status==="found"?resolution.binding:null}function resolveAuthorizedScopeBindingForSessionDetailed(input){let plan=readCurrentPlan(input.directory);if(!plan)return{status:"not_declared"};let matches=[],expired=[],expiredTotal=0;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let resolution=resolveAuthorizedScopeBindingForPlanDetailed({directory:input.directory,plan,taskId:task.id,activeSessionId:input.activeSessionId});if(resolution.status==="overloaded")return resolution;if(resolution.status==="ambiguous")return resolution;if(resolution.status==="found")matches.push(resolution.binding);if(resolution.status==="expired")expired.push(...resolution.candidates),expiredTotal+=resolution.totalCandidates;if(matches.length>1)return{status:"ambiguous",candidates:matches.slice(0,8),totalCandidates:matches.length}}if(matches[0])return{status:"found",binding:matches[0]};return expired.length>0?{status:"expired",candidates:expired.slice(0,8),totalCandidates:expiredTotal}:{status:"not_declared"}}function readPrFeedbackBindingFile(directory,filePath,activeSessionId,taskId){try{let leaf=fs17.lstatSync(filePath);if(!leaf.isFile()||leaf.isSymbolicLink())return null;if(normalizePathForComparison(fs17.realpathSync(filePath))!==normalizePathForComparison(filePath))return null}catch{return null}let nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(filePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}let raw="";try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile()||stat5.size>MAX_SCOPE_BYTES)return null;let buffer=Buffer.alloc(stat5.size);fs17.readSync(fd,buffer,0,stat5.size,0),raw=buffer.toString("utf8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}let parsed;try{parsed=validateScopeBindingPayload(directory,JSON.parse(raw))}catch{return null}if(!parsed)return null;if(hasScopeBindingDenyOverlay(parsed))return null;let now=Date.now();if(parsed.source!=="pr_feedback"||taskId!==void 0&&parsed.taskId!==taskId||parsed.ownerSessionId!==activeSessionId||parsed.activation!=="active"||typeof parsed.dispatchCallId!=="string"||!parsed.dispatchCallId||parsed.ownerMessageId!==parsed.dispatchCallId||typeof parsed.parentOwnerSessionId!=="string"||!parsed.parentOwnerSessionId||parsed.ownerSessionId===parsed.parentOwnerSessionId||parsed.parentCallId!==parsed.dispatchCallId||parsed.workflowSessionId!==parsed.parentOwnerSessionId||typeof parsed.workflowRevisionDigest!=="string"||!parsed.workflowRevisionDigest||parsed.planId!==`pr-feedback:${parsed.workflowSessionId}`||parsed.planStructureHash!==parsed.workflowRevisionDigest||parsed.declaredAt>now||parsed.expiresAt<=now||parsed.lifecycleState!=="live")return null;let expectedPath=getBindingFilePath(directory,parsed);if(normalizePathForComparison(expectedPath)!==normalizePathForComparison(filePath))return null;return parsed}function resolveAuthorizedPrFeedbackScopeBindingFromDisk(input){if(!input.activeSessionId.trim())return null;let scopesDir=getScopesDir(input.directory);if(!isScopesDirSafe(input.directory,scopesDir))return null;if(!migrateLegacyBindingsSync(input.directory))return null;let candidates;if(input.taskId){if(!isSafeTaskId(input.taskId))return null;try{let names=fs17.readdirSync(scopesDir);if(names.length>MAX_BINDING_FILES_TO_SCAN)return null;candidates=names.filter((name)=>name.startsWith(exactBindingPrefix(input.taskId))&&name.endsWith(".json")).map((name)=>path24.join(scopesDir,name))}catch{return null}}else try{let names=fs17.readdirSync(scopesDir);if(names.length>MAX_BINDING_FILES_TO_SCAN)return null;candidates=names.filter((name)=>name.startsWith("binding-")&&name.endsWith(".json")).map((name)=>path24.join(scopesDir,name))}catch{return null}let matches=candidates.map((candidate)=>readPrFeedbackBindingFile(input.directory,candidate,input.activeSessionId,input.taskId)).filter((binding)=>binding!==null);if(matches.length!==1)return null;return registerScopeBinding(matches[0]).ok?matches[0]:null}async function atomicWrite(targetPath,content){await atomicWriteSwarmFile(targetPath,content)}function atomicWriteSync(targetPath,content){atomicWriteSwarmFileSync(targetPath,content)}function readScopeFromDisk(directory,taskId){if(!isSafeTaskId(taskId))return null;let scopesDir=getScopesDir(directory);if(!isScopesDirSafe(directory,scopesDir))return null;let scopePath=getScopeFilePath(directory,taskId),nofollow=fs17.constants.O_NOFOLLOW??0,fd;try{fd=fs17.openSync(scopePath,fs17.constants.O_RDONLY|nofollow)}catch{return null}let raw;try{let stat5=fs17.fstatSync(fd);if(!stat5.isFile())return null;if(stat5.size>MAX_SCOPE_BYTES)return null;let buf=Buffer.alloc(stat5.size);fs17.readSync(fd,buf,0,stat5.size,0),raw=buf.toString("utf-8")}catch{return null}finally{try{fs17.closeSync(fd)}catch{}}if(!raw.trim())return null;let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(parsed.version!==SCOPE_SCHEMA_VERSION)return null;if(parsed.taskId!==taskId)return null;let now=Date.now();if(typeof parsed.declaredAt!=="number"||parsed.declaredAt>now)return null;if(typeof parsed.expiresAt!=="number"||now>=parsed.expiresAt)return null;if(!Array.isArray(parsed.files))return null;if(parsed.files.length>MAX_FILES_PER_SCOPE)return null;let files=parsed.files.filter((f)=>typeof f==="string");return files.length>0?files:null}function readPlanScope(directory,taskId){if(!isSafeTaskId(taskId))return null;try{let planPath=path24.join(directory,".swarm","plan.json"),stat5=fs17.statSync(planPath);if(!stat5.isFile())return null;if(stat5.size>MAX_PLAN_BYTES)return null;let raw=fs17.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);for(let phase of plan.phases??[])for(let task of phase.tasks??[]){if(task.id!==taskId)continue;let ft=task.files_touched;if(Array.isArray(ft)&&ft.length>0){if(ft.length>MAX_FILES_PER_SCOPE)return null;return ft.filter((f)=>typeof f==="string")}if(typeof ft==="string"&&ft.length>0)return[ft];return null}return null}catch{return null}}function clearScopeForTask(directory,taskId){if(!isSafeTaskId(taskId))return;try{assertProjectRoot(directory),fs17.unlinkSync(getScopeFilePath(directory,taskId))}catch{}}function clearAllScopes(directory){try{assertProjectRoot(directory),fs17.rmSync(getScopesDir(directory),{recursive:!0,force:!0})}catch{}}function resolveScopeWithFallbacks(input){let{directory,taskId,inMemoryScope,pendingMapScope}=input;if(inMemoryScope&&inMemoryScope.length>0)return inMemoryScope;if(taskId){let disk=readScopeFromDisk(directory,taskId);if(disk&&disk.length>0)return disk;let plan=readPlanScope(directory,taskId);if(plan&&plan.length>0)return plan}if(pendingMapScope&&pendingMapScope.length>0)return pendingMapScope;return null}var import_proper_lockfile3,SCOPE_SCHEMA_VERSION=1,DEFAULT_TTL_MS=86400000,LOCK_STALE_MS2=30000,SCOPES_DIR=".swarm/scopes",MAX_FILES_PER_SCOPE=1e4,MAX_PLAN_BYTES=10485760,MAX_SCOPE_BYTES=2097152,MAX_BINDING_FILES_TO_SCAN=1e4,MAX_TOMBSTONE_AGE_MS=604800000,MAX_DURABLE_TOMBSTONES=256,liveBindingCapacity,bindingFileScanCapacity,maintenanceFileScanCapacity,MAX_MAINTENANCE_JOBS=64,maintenanceJobs,lockfileWithSync,syncLockWait,WINDOWS_RESERVED,SCOPE_BINDING_AUTO_REVIVE_WINDOW_MS=86400000,_scopePersistenceInternals;var init_scope_persistence=__esm(()=>{init_plan_schema();init_core_events();init_ledger();init_utils3();init_atomic_write();init_project_boundary();init_scope_binding();import_proper_lockfile3=__toESM(require_proper_lockfile(),1),liveBindingCapacity=MAX_PENDING_SCOPE_BINDINGS,bindingFileScanCapacity=MAX_BINDING_FILES_TO_SCAN,maintenanceFileScanCapacity=MAX_BINDING_FILES_TO_SCAN*2,maintenanceJobs=new Map,lockfileWithSync=import_proper_lockfile3.default,syncLockWait=new Int32Array(new SharedArrayBuffer(4));WINDOWS_RESERVED=new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]);_scopePersistenceInternals={get liveBindingCapacity(){return liveBindingCapacity},set liveBindingCapacity(value){liveBindingCapacity=Math.max(1,Math.floor(value))},get bindingFileScanCapacity(){return bindingFileScanCapacity},set bindingFileScanCapacity(value){bindingFileScanCapacity=Math.max(1,Math.floor(value))},get maintenanceFileScanCapacity(){return maintenanceFileScanCapacity},set maintenanceFileScanCapacity(value){maintenanceFileScanCapacity=Math.max(1,Math.floor(value))}}});var exports_core3={};__export(exports_core3,{writeLaneProfileToDiskReal:()=>writeLaneProfileToDiskReal,shortenWorktreePath:()=>shortenWorktreePath,resolveWorktreeBaseDir:()=>resolveWorktreeBaseDir,removeWorktree:()=>removeWorktree,removeLaneProfileFromDiskReal:()=>removeLaneProfileFromDiskReal,provisionWorktree:()=>provisionWorktree,makeWorktreeBranchName:()=>makeWorktreeBranchName,isPathUnderSwarmWorktreeBase:()=>isPathUnderSwarmWorktreeBase,isCleanWorktree:()=>isCleanWorktree,cleanUntrackedFiles:()=>cleanUntrackedFiles,checkPathBudget:()=>checkPathBudget,autoCommitDirty:()=>autoCommitDirty,assertCleanWorkingTree:()=>assertCleanWorkingTree,_internals:()=>_internals16});import*as fs18 from"node:fs";import*as fsPromises3 from"node:fs/promises";import*as os5 from"node:os";import*as path25 from"node:path";async function writeLaneProfileToDiskReal(worktreePath,laneIndex,envOverrides){let lines=[];for(let[key,value]of Object.entries(envOverrides)){if(value===null)continue;if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))continue;if(value.includes(`
|
|
227
227
|
`)||value.includes("\r")){log("writeLaneProfileToDisk: skipping env var with newline in value",{key});continue}lines.push(`${key}=${value}`)}if(lines.length===0)return;let lanesDir=path25.join(worktreePath,".swarm","lanes");await fs18.promises.mkdir(lanesDir,{recursive:!0});let envPath=path25.join(lanesDir,`${laneIndex}.env`);await fs18.promises.writeFile(envPath,`${lines.join(`
|
|
228
228
|
`)}
|
|
229
229
|
`,"utf-8")}async function removeLaneProfileFromDiskReal(worktreePath,laneIndex){let envPath=path25.join(worktreePath,".swarm","lanes",`${laneIndex}.env`);try{await fs18.promises.unlink(envPath)}catch(err){if(err.code!=="ENOENT")log(`[worktree] Failed to remove lane profile ${envPath}: ${err.message}`)}}async function runGit2(args2,cwd,timeoutMs=WORKTREE_TIMEOUT_MS){let proc;try{proc=_internals16.bunSpawn([_internals16.resolveGitExecutable(),...args2],{cwd,timeout:timeoutMs,stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,LC_ALL:"C"}})}catch(error49){return{exitCode:GIT_SPAWN_FAILURE_EXIT_CODE,stdout:"",stderr:`git ${args2[0]??"command"} could not start in ${cwd}: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let exitCode=await proc.exited,stdout=await proc.stdout.text(),stderr=await proc.stderr.text();return{exitCode,stdout,stderr}}finally{try{proc.kill()}catch{}}}async function checkPathBudget(worktreeRoot,directory){if(_internals16.platform!=="win32")return{ok:!0};let longPaths;try{longPaths=await _internals16.getCoreLongPaths(directory)}catch{}if(longPaths==="true")return{ok:!0};let proc;try{proc=_internals16.bunSpawn([_internals16.resolveGitExecutable(),"ls-files"],{cwd:directory,timeout:WORKTREE_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"ignore",env:{...process.env,LC_ALL:"C"}})}catch{return{ok:!0}}try{let exitCode=await proc.exited,stdout=await proc.stdout.text();if(exitCode!==0||stdout.trim().length===0)return{ok:!0};let files=stdout.split(/\r?\n/),longest=0;for(let file2 of files)if(file2.length>longest)longest=file2.length;let totalPathLength=worktreeRoot.length+1+longest;if(totalPathLength>=WIN_PATH_BUDGET)return{ok:!1,error:`Total path budget exceeded: worktree root "${worktreeRoot}" (${worktreeRoot.length} chars) + longest file "${files.find((f)=>f.length===longest)}" (${longest} chars) = ${totalPathLength} chars (budget: ${WIN_PATH_BUDGET})`,suggestion:"Set config.worktree_dir to a shorter absolute path, or let the auto-shorten feature relocate the worktree to the system temp directory."};return{ok:!0}}finally{try{proc.kill()}catch{}}}function shortenWorktreePath(_directory,sessionId,laneId){let tmp=_internals16.osTmpdir();try{tmp=fs18.realpathSync(tmp)}catch{}return path25.join(tmp,"swwt",sessionId,laneId)}function makeWorktreeBranchName(sessionId,id,options){return buildSwarmBranchName(sessionId,id,options.purpose,options.branchStyle==="legacy-lane"&&options.purpose==="lane")}function resolveWorktreeBaseDir(directory,worktreeDir){return worktreeDir?path25.resolve(directory,worktreeDir):path25.resolve(path25.dirname(directory),SWARM_WORKTREE_DIR_NAME)}function isPathUnderSwarmWorktreeBase(targetPath,directory,worktreeDirOverrides=[]){let caseInsensitive=process.platform==="win32",realTarget;try{realTarget=fs18.realpathSync(path25.resolve(directory,targetPath))}catch{return!1}let bases=[resolveWorktreeBaseDir(directory),...worktreeDirOverrides.map((d)=>resolveWorktreeBaseDir(directory,d))],cmpTarget=caseInsensitive?realTarget.toLowerCase():realTarget;return bases.some((base)=>{let realBase;try{realBase=fs18.realpathSync(base)}catch{realBase=path25.resolve(base)}let cmpBase=caseInsensitive?realBase.toLowerCase():realBase;if(cmpTarget===cmpBase)return!0;let rel=path25.relative(cmpBase,cmpTarget);return rel.length>0&&!rel.startsWith("..")&&!path25.isAbsolute(rel)})}async function provisionWorktree(directory,id,sessionId,options){let branchName=makeWorktreeBranchName(sessionId,id,options);if(!matchSwarmLaneBranch(branchName))return{error:`Refusing to provision worktree: branch "${branchName}" does not match the swarm lane grammar, so lane permission scoping could not recognise it and the lane would hang on the first external-directory prompt. This is almost always an invalid sessionId ("${sessionId}"); it must look like "ses_" followed by letters/digits, and the execution-unit id ("${id}") must be a single path segment.`};let worktreePath=path25.resolve(resolveWorktreeBaseDir(directory,options.worktreeDir),sessionId,id),budgetResult=await checkPathBudget(worktreePath,directory);if(budgetResult.ok===!1)if(options.worktreeDir)advisoryWarn(`[swarm] Path budget warning: ${budgetResult.error} ${budgetResult.suggestion}`);else{let shortPath=shortenWorktreePath(directory,sessionId,id);if((await checkPathBudget(shortPath,directory)).ok===!1)return{error:budgetResult.error};worktreePath=shortPath}if((await runGit2(["show-ref","--verify","--quiet",`refs/heads/${branchName}`],directory)).exitCode===0){let listResult=await runGit2(["worktree","list","--porcelain"],directory),normalizeGitPath=(p)=>{let lexical=p.replace(/\\/g,"/").replace(/\/+$/,"");try{return fs18.realpathSync(p).replace(/\\/g,"/").replace(/\/+$/,"")}catch{return lexical}},expectedPath=normalizeGitPath(worktreePath),entries=[];if(listResult.exitCode!==0){let raw=listResult.stderr.trim()||listResult.stdout.trim();return{error:`worktree enumeration failed: ${raw.length>500?`${raw.slice(0,500)}... (truncated)`:raw}`}}let parsePorcelain=(stdout)=>{let parsed=[],cur={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
|
|
@@ -559,10 +559,10 @@ Use this data to avoid repeating known failure patterns.`,summaryText=summaries.
|
|
|
559
559
|
`),diffLines=computeLcsDiff(recordedLines,currentLines),MAX_DIFF_LINES=300,diffText=diffLines.length<=MAX_DIFF_LINES?diffLines.join(`
|
|
560
560
|
`):diffLines.slice(0,MAX_DIFF_LINES).join(`
|
|
561
561
|
`)+`
|
|
562
|
-
... (diff truncated — `+String(diffLines.length-MAX_DIFF_LINES)+" more lines)",changedSectionsSet=new Set,currentSection="";for(let line of diffLines){let headingMatch=line.slice(1).match(/^##\s+(.+)$/);if(headingMatch)currentSection=headingMatch[1].trim();if(line.length>0&&(line[0]==="+"||line[0]==="-")){if(currentSection)changedSectionsSet.add(currentSection)}}return{diff:diffText,changedSections:Array.from(changedSectionsSet)}}function computeLcsDiff(oldLines,newLines){let m=oldLines.length,n=newLines.length,dp=Array.from({length:m+1},()=>Array(n+1).fill(0));for(let i2=1;i2<=m;i2++)for(let j2=1;j2<=n;j2++)if(oldLines[i2-1]===newLines[j2-1])dp[i2][j2]=dp[i2-1][j2-1]+1;else dp[i2][j2]=Math.max(dp[i2-1][j2],dp[i2][j2-1]);let entries=[],i=m,j=n;while(i>0||j>0)if(i>0&&j>0&&oldLines[i-1]===newLines[j-1])entries.unshift({type:"unchanged",line:oldLines[i-1]}),i--,j--;else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j]))entries.unshift({type:"add",line:newLines[j-1]}),j--;else entries.unshift({type:"remove",line:oldLines[i-1]}),i--;return entries.map((entry)=>{if(entry.type==="unchanged")return` ${entry.line}`;if(entry.type==="add")return`+${entry.line}`;return`-${entry.line}`})}var _internals34;var init_spec_hash=__esm(()=>{init_effective_spec();_internals34={computeSpecDiff,computeSpecHash,isObligationPreserving,isSpecStale,readEffectiveSpecSync}});import{closeSync as closeSync7,copyFileSync,existsSync as existsSync24,fsyncSync as fsyncSync3,mkdirSync as mkdirSync20,openSync as openSync7,readdirSync as readdirSync7,renameSync as renameSync12,unlinkSync as unlinkSync12,writeFileSync as writeFileSync13}from"node:fs";import*as fsPromises4 from"node:fs/promises";import*as path45 from"node:path";function derivePhaseStatusesInPlace(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((t)=>t.status==="completed"))phase.status="complete";else if(tasks.some((t)=>t.status==="in_progress"))phase.status="in_progress";else if(tasks.some((t)=>t.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function statusRank(s){switch(s){case"closed":return 5;case"completed":return 4;case"blocked":return 3;case"in_progress":return 2;case"pending":return 1;default:return 0}}function mergeStatusesTakingPrecedence(validated,replayed,ledgerStatusTaskIds){let projected=structuredClone(validated),replayedByTaskId=new Map;for(let phase of replayed.phases)for(let task of phase.tasks)if(ledgerStatusTaskIds.has(task.id))replayedByTaskId.set(task.id,task.status);for(let phase of projected.phases)for(let task of phase.tasks){let replayedStatus=replayedByTaskId.get(task.id);if(replayedStatus&&statusRank(replayedStatus)>statusRank(task.status))task.status=replayedStatus}return derivePhaseStatusesInPlace(projected),projected}function collectLedgerStatusTaskIds(events){let statusTaskIds=new Set;for(let event of events)if(event.event_type==="task_status_changed"&&typeof event.task_id==="string")statusTaskIds.add(event.task_id);return statusTaskIds}async function retryCasWithBackoff(directory,eventInput,options){let maxRetries=options.maxRetries??CAS_MAX_RETRIES,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let base=Math.min(CAS_BACKOFF_START_MS*2**(attempt-1),CAS_BACKOFF_CAP_MS),jitter=base*CAS_BACKOFF_JITTER*(Math.random()*2-1),delayMs=Math.max(1,Math.round(base+jitter));if(emit("plan_ledger_cas_retry",{attempt,expectedHashPrefix:currentExpected.slice(0,8),delayMs}),await new Promise((resolve25)=>setTimeout(resolve25,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function loadPlanJsonOnly(directory){try{return await parsePlanJsonCached(directory)}catch(error49){warn(`Plan validation failed for .swarm/plan.json: ${error49 instanceof Error?error49.message:String(error49)}`)}return null}function compareTaskIds(a,b){let partsA=a.split(".").map((n)=>parseInt(n,10)),partsB=b.split(".").map((n)=>parseInt(n,10)),maxLen=Math.max(partsA.length,partsB.length);for(let i=0;i<maxLen;i++){let numA=partsA[i]??0,numB=partsB[i]??0;if(numA!==numB)return numA-numB}return 0}async function getLatestLedgerHash(directory){try{let events=await readLedgerEvents(directory);if(events.length===0)return"";return events[events.length-1].plan_hash_after}catch{return""}}async function surfaceLedgerStaleIfPersisted(directory,plan){let resolvedWorkspace=path45.resolve(directory);if(!ledgerStaleWorkspaces.has(resolvedWorkspace))return plan;try{let planHash=
|
|
563
|
-
${markdown}`,mdPath=path45.join(swarmDir,"plan.md"),mdTempPath=path45.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync12(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}async function loadPlan(directory,cache2){let planJsonContent=await readSwarmFileAsync(directory,"plan.json",cache2);if(planJsonContent!==null)if(planJsonContent.includes("\x00")||planJsonContent.includes("�"))warn("Plan rejected: .swarm/plan.json contains null bytes or invalid encoding");else try{let validated=await parsePlanJsonCached(directory);if(validated===null)warn("[loadPlan] plan.json disappeared during cached parse. Falling back to plan.md migration or ledger recovery.");else{if(!await isPlanMdInSync(directory,validated,cache2))try{await _internals35.regeneratePlanMarkdown(directory,validated)}catch(regenError){warn(`Failed to regenerate plan.md: ${regenError instanceof Error?regenError.message:String(regenError)}. Proceeding with plan.json only.`)}if(await ledgerExists(directory)){let planHash=computePlanHash(validated),ledgerHash=await getLatestLedgerHash(directory),resolvedWorkspace=path45.resolve(directory);if(!startupLedgerCheckedWorkspaces.has(resolvedWorkspace)){if(startupLedgerCheckedWorkspaces.add(resolvedWorkspace),ledgerHash!==""&&planHash!==ledgerHash){let currentPlanId=derivePlanId(validated),ledgerEvents=await readLedgerEvents(directory),firstEvent=ledgerEvents.length>0?ledgerEvents[0]:null;if(firstEvent&&firstEvent.plan_id!==currentPlanId)warn(`[loadPlan] Ledger identity mismatch (ledger: ${firstEvent.plan_id}, plan: ${currentPlanId}) — skipping ledger rebuild (migration detected). Use /swarm reset-session to reinitialize the ledger.`);else{warn("[loadPlan] plan.json is stale (hash mismatch with ledger) — rebuilding from ledger. If this recurs, run /swarm reset-session to clear stale session state.");try{let{plan:rebuilt,truncated}=await replayFromLedgerWithStatus(directory);if(truncated){let runtimeStale=validated;return runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason="Ledger truncated: a malformed line stopped replay before the tail, so the ledger could only be reconstructed up to the corruption. plan.json was PRESERVED (not rolled back to the prefix-only projection) and the corrupted suffix was quarantined to .swarm/plan-ledger.quarantine.*. Verify state, then run /swarm reset-session if this persists.",ledgerStaleWorkspaces.add(resolvedWorkspace),criticalWarn("[loadPlan] Ledger truncated (poison line detected) — preserving plan.json instead of rolling back to the prefix-only ledger projection. Durable post-poison events remain in plan.json. Corrupted suffix quarantined to .swarm/plan-ledger.quarantine.*. Run /swarm reset-session after verifying state if this persists."),runtimeStale}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"ledger_hash_mismatch_recovery"}),warn("[loadPlan] Rebuilt plan from ledger. Checkpoint available at .swarm/plan-export/SWARM_PLAN.md if it exists."),rebuilt}catch(replayError){try{let approved=await loadLastApprovedPlan(directory,currentPlanId);if(approved){await rebuildPlan(directory,approved.plan,{reason:"approved_snapshot_fallback"});try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;return warn(`[loadPlan] Ledger replay failed (${replayError instanceof Error?replayError.message:String(replayError)}) — recovered from critic-approved snapshot seq=${approved.seq} (approval phase=${approvedPhase??"unknown"}, timestamp=${approved.timestamp}). This may roll the plan back to an earlier phase — verify before continuing.`),approved.plan}}catch{}{let runtimeStale=validated;runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason=`Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error?replayError.message:String(replayError)}`,ledgerStaleWorkspaces.add(resolvedWorkspace)}warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error?replayError.message:String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`)}}}}else if(ledgerHash!==""&&planHash!==ledgerHash){if(process.env.DEBUG_SWARM)console.warn(`[loadPlan] Ledger hash mismatch during active session for ${resolvedWorkspace} — skipping rebuild (startup check already performed).`)}}if(validated.specHash){let staleResult=await isSpecStale(directory,validated);if(staleResult.stale){let runtimePlan=validated;if(runtimePlan._specStale=!0,runtimePlan._specStaleReason=staleResult.reason,!await isObligationPreserving(directory)){try{assertProjectRoot(directory);let diffInfo=computeSpecDiff(directory),specStalenessPath=path45.join(directory,".swarm","spec-staleness.json");await fsPromises4.writeFile(specStalenessPath,JSON.stringify({type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason,planTitle:validated.title,diff:diffInfo?.diff??null,changedSections:diffInfo?.changedSections??[]},null,2),"utf-8"),invalidateCachedArtifact(specStalenessPath)}catch{}try{assertProjectRoot(directory);let event={type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason??"unknown",planTitle:validated.title};appendCoreEventSync(directory,{...event})}catch{}}}}return await surfaceLedgerStaleIfPersisted(directory,validated)}}catch(error49){warn(`[loadPlan] plan.json validation failed: ${error49 instanceof Error?error49.message:String(error49)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);let rawPlanId=null;try{let rawParsed=JSON.parse(planJsonContent);if(typeof rawParsed?.swarm==="string"&&typeof rawParsed?.title==="string")rawPlanId=derivePlanId(rawParsed)}catch{}if(await ledgerExists(directory)){let ledgerEventsForCatch=await readLedgerEvents(directory),catchFirstEvent=ledgerEventsForCatch.length>0?ledgerEventsForCatch[0]:null;if(!(rawPlanId===null||catchFirstEvent===null||catchFirstEvent.plan_id===rawPlanId))warn(`[loadPlan] Ledger identity mismatch in validation-failure path (ledger: ${catchFirstEvent?.plan_id}, plan: ${rawPlanId}) — skipping ledger rebuild (migration detected).`);else if(catchFirstEvent!==null&&rawPlanId!==null){let rebuilt=await replayFromLedger(directory);if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"validation_failure_recovery"}),warn("[loadPlan] Rebuilt plan from ledger after validation failure. Projection was stale."),rebuilt}}let planMdContent2=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent2!==null){let migrated=migrateLegacyPlan(planMdContent2),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json");if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return migrated}}let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent!==null){let migrated=migrateLegacyPlan(planMdContent);return await savePlan(directory,migrated),migrated}if(await ledgerExists(directory)){let resolvedDir=path45.resolve(directory),existingMutex=recoveryMutexes.get(resolvedDir);if(existingMutex){await existingMutex;let postRecoveryPlan=await _internals35.loadPlanJsonOnly(directory);if(postRecoveryPlan)return postRecoveryPlan}let resolveRecovery,mutex=new Promise((r)=>{resolveRecovery=r});recoveryMutexes.set(resolvedDir,mutex);try{let rebuilt=await replayFromLedger(directory);if(rebuilt){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,rebuilt,"load_plan_rebuild_from_ledger","rebuild plan from ledger replay");if(removedCount>0)rebuilt._midLoadRemovals={count:removedCount,source:"load_plan_rebuild_from_ledger"};return rebuilt}try{let anchorEvents=await readLedgerEvents(directory);if(anchorEvents.length===0)return warn("[loadPlan] Ledger present but no events readable — refusing approved-snapshot recovery (cannot verify plan identity)."),null;let expectedPlanId=anchorEvents[0].plan_id,approved=await loadLastApprovedPlan(directory,expectedPlanId);if(approved){let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;warn(`[loadPlan] Ledger replay returned no plan — recovered from critic-approved snapshot seq=${approved.seq} timestamp=${approved.timestamp} (approval phase=${approvedPhase??"unknown"}). This may roll the plan back to an earlier phase — verify before continuing.`);let{removedCount:snapshotRemovedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot");if(snapshotRemovedCount>0)approved.plan._midLoadRemovals={count:snapshotRemovedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return approved.plan}}catch(recoveryError){warn(`[loadPlan] Approved-snapshot recovery failed: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`)}}finally{resolveRecovery(),recoveryMutexes.delete(resolvedDir)}}return null}async function savePlanWithAutoAcknowledgedRemovals(directory,plan,source,reason,options){let existing=await _internals35.loadPlanJsonOnly(directory),newIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)newIds.add(task.id);let removedIds=[];if(existing){for(let phase of existing.phases)for(let task of phase.tasks)if(!newIds.has(task.id))removedIds.push(task.id)}return await savePlan(directory,plan,{...options??{},acknowledged_removals:{ids:removedIds,reason,source}}),{removedCount:removedIds.length}}async function savePlan(directory,plan,options){if(directory===null||directory===void 0||typeof directory!=="string"||directory.trim().length===0)throw Error("Invalid directory: directory must be a non-empty string");if(assertProjectRoot(directory),!options?.planLockAlreadyHeld){let lockResult=await tryAcquireLock(directory,"plan.json","plan-manager",`save-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{await savePlan(directory,plan,{...options,planLockAlreadyHeld:!0});return}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}let validated=PlanSchema.parse(plan),requestedForStaleProjectionReconcile=options?.staleProjectionReconcile!==void 0?PlanSchema.parse(plan):null;if(requestedForStaleProjectionReconcile)derivePhaseStatusesInPlace(requestedForStaleProjectionReconcile);if(options?.preserveCompletedStatuses!==!1)try{let currentPlan2=await _internals35.loadPlanJsonOnly(directory);if(currentPlan2){let completedTaskIds=new Set;for(let phase of currentPlan2.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.add(task.id);if(completedTaskIds.size>0){for(let phase of validated.phases)for(let task of phase.tasks)if(completedTaskIds.has(task.id)&&task.status!=="completed")task.status="completed"}}}catch{}derivePhaseStatusesInPlace(validated);let currentPlan=await _internals35.loadPlanJsonOnly(directory),planId=derivePlanId(validated),planHashForInit=computePlanHash(validated);if(!await ledgerExists(directory))try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated)}catch(initErr){let msg=initErr instanceof Error?initErr.message:String(initErr);if(!/already initialized/i.test(msg))throw initErr}else{let existingEvents=await readLedgerEvents(directory);if(existingEvents.length>0&&existingEvents[0].plan_id!==planId){let swarmDir2=path45.resolve(directory,".swarm"),oldLedgerPath=path45.join(swarmDir2,"plan-ledger.jsonl"),oldLedgerBackupPath=path45.join(swarmDir2,`plan-ledger.backup-${Date.now()}-${Math.floor(Math.random()*1e9)}.jsonl`),backupExists=!1;if(existsSync24(oldLedgerPath))try{options?.preCommitCheck?.(),renameSync12(oldLedgerPath,oldLedgerBackupPath),backupExists=!0}catch(renameErr){throw Error(`[savePlan] Cannot reinitialize ledger: could not move old ledger aside (rename failed: ${renameErr instanceof Error?renameErr.message:String(renameErr)}). The existing ledger has plan_id="${existingEvents[0].plan_id}" which does not match the current plan="${planId}". To proceed, close any programs that may have the ledger file open, or run /swarm reset-session to clear the ledger.`)}let initSucceeded=!1;if(backupExists)try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated),initSucceeded=!0}catch(initErr){if(String(initErr).includes("already initialized"))try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}else{if(existsSync24(oldLedgerBackupPath))try{renameSync12(oldLedgerBackupPath,oldLedgerPath)}catch{copyFileSync(oldLedgerBackupPath,oldLedgerPath);try{unlinkSync12(oldLedgerBackupPath)}catch{}}throw initErr}}if(initSucceeded&&backupExists){let archivePath=path45.join(swarmDir2,`plan-ledger.archived-${Date.now()}-${Math.floor(Math.random()*1e9)}.jsonl`);try{renameSync12(oldLedgerBackupPath,archivePath),warn(`[savePlan] Ledger identity mismatch (was "${existingEvents[0].plan_id}", now "${planId}") — archived old ledger to ${archivePath} and reinitializing.`)}catch(renameErr){warn(`[savePlan] Could not archive old ledger (rename failed: ${renameErr instanceof Error?renameErr.message:String(renameErr)}). Old ledger may still exist at ${oldLedgerBackupPath}.`);try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}}}else if(!initSucceeded&&backupExists)try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}let MAX_ARCHIVED_SIBLINGS=5;try{let archivedSiblings=readdirSync7(swarmDir2).filter((f)=>f.startsWith("plan-ledger.archived-")&&f.endsWith(".jsonl")).sort();if(archivedSiblings.length>MAX_ARCHIVED_SIBLINGS){let toRemove=archivedSiblings.slice(0,archivedSiblings.length-MAX_ARCHIVED_SIBLINGS);for(let file2 of toRemove)try{unlinkSync12(path45.join(swarmDir2,file2))}catch{}}}catch{}}}if(options?.staleProjectionReconcile){if(!currentPlan)throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: no current plan.json projection exists.");let comparableCurrent=PlanSchema.parse(currentPlan);if(derivePhaseStatusesInPlace(comparableCurrent),JSON.stringify(comparableCurrent)!==JSON.stringify(requestedForStaleProjectionReconcile))throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: manager rejected content that is not the exact unchanged plan.json projection.");let events=await readLedgerEvents(directory),tail=events[events.length-1],expected=options.staleProjectionReconcile;if(!tail||tail.seq!==expected.expectedSeq||tail.plan_hash_after!==expected.expectedLedgerHash||events[0]?.plan_id!==planId)throw new PlanConcurrentModificationError("RECONCILE_LEDGER_PROJECTION_STALE: the ledger identity or tail changed before the recovery snapshot could be appended.");try{if((await readLedgerEventsWithIntegrity(directory)).truncated)await replaceTruncatedLedgerWithRecoveryRoot(directory,validated,{seq:expected.expectedSeq,ledgerHash:expected.expectedLedgerHash});else await takeSnapshotEvent(directory,validated,{planHashAfter:computePlanHash(validated),source:"save_plan_stale_projection_reconcile",expectedSeq:expected.expectedSeq,expectedLedgerHash:expected.expectedLedgerHash})}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`RECONCILE_LEDGER_PROJECTION_STALE: ${error49.message}`);throw error49}}let currentHash=computeCurrentPlanHash(directory),hashAfter=computePlanHash(validated);if(currentPlan){let oldTaskMap=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldTaskMap.set(task.id,{phase:task.phase,status:task.status});let newTaskIds=new Set;for(let phase of validated.phases)for(let task of phase.tasks)newTaskIds.add(task.id);let missingTasks=[];for(let[id,info]of oldTaskMap.entries())if(!newTaskIds.has(id))missingTasks.push({id,phase:info.phase,status:info.status});let ack=options?.acknowledged_removals;if(missingTasks.length>0){if(!ack)throw new PlanTaskRemovalNotAcknowledgedError(missingTasks);if(typeof ack.reason!=="string"||ack.reason.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.reason must be a non-empty string.");if(typeof ack.source!=="string"||ack.source.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.source must be a non-empty string.");let ackSet=new Set(ack.ids),missingIdsSet=new Set(missingTasks.map((t)=>t.id)),unacked=missingTasks.filter((t)=>!ackSet.has(t.id));if(unacked.length>0)throw new PlanTaskRemovalNotAcknowledgedError(unacked);for(let id of ack.ids)if(!missingIdsSet.has(id))throw Error(`PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals contains "${id}" but that task is not missing from the plan.`);try{for(let missing of missingTasks){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_removed",task_id:missing.id,phase_id:missing.phase,from_status:missing.status,source:ack.source,payload:{reason:ack.reason,source:ack.source}},capturedTaskId=missing.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals35.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases)if(p.tasks.some((x)=>x.id===capturedTaskId))return!0;return!1}})}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}try{for(let phase of validated.phases)for(let task of phase.tasks){let oldTask=oldTaskMap.get(task.id);if(oldTask&&oldTask.status!==task.status){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_status_changed",task_id:task.id,phase_id:phase.id,from_status:oldTask.status,to_status:task.status,source:"savePlan"},capturedFromStatus=oldTask.status,capturedTaskId=task.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals35.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases){let t=p.tasks.find((x)=>x.id===capturedTaskId);if(t)return t.status===capturedFromStatus}return!1}})}}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}let ledgerStatusTaskIds=collectLedgerStatusTaskIds(await readLedgerEvents(directory)),replayedBeforeProjection=await replayFromLedger(directory),projectionCandidate=replayedBeforeProjection?mergeStatusesTakingPrecedence(validated,replayedBeforeProjection,ledgerStatusTaskIds):validated;if(replayedBeforeProjection&&computePlanHash(replayedBeforeProjection)!==computePlanHash(projectionCandidate))options?.preCommitCheck?.(),await takeSnapshotEvent(directory,projectionCandidate,{planHashAfter:computePlanHash(projectionCandidate),source:"savePlan_structural_projection"});let projectedPlan=projectionCandidate,SNAPSHOT_INTERVAL=50,latestSeq=await getLatestLedgerSeq(directory);if(!options?.preCommitCheck&&latestSeq>0&&latestSeq%SNAPSHOT_INTERVAL===0)await takeSnapshotWithRetry(directory,projectedPlan,{planHashAfter:computePlanHash(projectedPlan),source:"savePlan_manager"});let swarmDir=path45.resolve(directory,".swarm"),planPath=path45.join(swarmDir,"plan.json"),tempPath=path45.join(swarmDir,`plan.json.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(tempPath,JSON.stringify(projectedPlan,null,2)),options?.preCommitCheck?.(),renameSync12(tempPath,planPath)}finally{try{unlinkSync12(tempPath)}catch{}}invalidateCachedArtifact(planPath);try{let markerPath=path45.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:projectedPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(projectedPlan),markdown=derivePlanMarkdown(projectedPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
562
|
+
... (diff truncated — `+String(diffLines.length-MAX_DIFF_LINES)+" more lines)",changedSectionsSet=new Set,currentSection="";for(let line of diffLines){let headingMatch=line.slice(1).match(/^##\s+(.+)$/);if(headingMatch)currentSection=headingMatch[1].trim();if(line.length>0&&(line[0]==="+"||line[0]==="-")){if(currentSection)changedSectionsSet.add(currentSection)}}return{diff:diffText,changedSections:Array.from(changedSectionsSet)}}function computeLcsDiff(oldLines,newLines){let m=oldLines.length,n=newLines.length,dp=Array.from({length:m+1},()=>Array(n+1).fill(0));for(let i2=1;i2<=m;i2++)for(let j2=1;j2<=n;j2++)if(oldLines[i2-1]===newLines[j2-1])dp[i2][j2]=dp[i2-1][j2-1]+1;else dp[i2][j2]=Math.max(dp[i2-1][j2],dp[i2][j2-1]);let entries=[],i=m,j=n;while(i>0||j>0)if(i>0&&j>0&&oldLines[i-1]===newLines[j-1])entries.unshift({type:"unchanged",line:oldLines[i-1]}),i--,j--;else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j]))entries.unshift({type:"add",line:newLines[j-1]}),j--;else entries.unshift({type:"remove",line:oldLines[i-1]}),i--;return entries.map((entry)=>{if(entry.type==="unchanged")return` ${entry.line}`;if(entry.type==="add")return`+${entry.line}`;return`-${entry.line}`})}var _internals34;var init_spec_hash=__esm(()=>{init_effective_spec();_internals34={computeSpecDiff,computeSpecHash,isObligationPreserving,isSpecStale,readEffectiveSpecSync}});import{closeSync as closeSync7,copyFileSync,existsSync as existsSync24,fsyncSync as fsyncSync3,mkdirSync as mkdirSync20,openSync as openSync7,readdirSync as readdirSync7,renameSync as renameSync12,unlinkSync as unlinkSync12,writeFileSync as writeFileSync13}from"node:fs";import*as fsPromises4 from"node:fs/promises";import*as path45 from"node:path";function derivePhaseStatusesInPlace(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((t)=>t.status==="completed"))phase.status="complete";else if(tasks.some((t)=>t.status==="in_progress"))phase.status="in_progress";else if(tasks.some((t)=>t.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function statusRank(s){switch(s){case"closed":return 5;case"completed":return 4;case"blocked":return 3;case"in_progress":return 2;case"pending":return 1;default:return 0}}function mergeStatusesTakingPrecedence(validated,replayed,ledgerStatusTaskIds){let projected=structuredClone(validated),replayedByTaskId=new Map;for(let phase of replayed.phases)for(let task of phase.tasks)if(ledgerStatusTaskIds.has(task.id))replayedByTaskId.set(task.id,task.status);for(let phase of projected.phases)for(let task of phase.tasks){let replayedStatus=replayedByTaskId.get(task.id);if(replayedStatus&&statusRank(replayedStatus)>statusRank(task.status))task.status=replayedStatus}return derivePhaseStatusesInPlace(projected),projected}function collectLedgerStatusTaskIds(events){let statusTaskIds=new Set;for(let event of events)if(event.event_type==="task_status_changed"&&typeof event.task_id==="string")statusTaskIds.add(event.task_id);return statusTaskIds}async function retryCasWithBackoff(directory,eventInput,options){let maxRetries=options.maxRetries??CAS_MAX_RETRIES,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter})}catch(error49){if(!(error49 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error49;attempt++;let base=Math.min(CAS_BACKOFF_START_MS*2**(attempt-1),CAS_BACKOFF_CAP_MS),jitter=base*CAS_BACKOFF_JITTER*(Math.random()*2-1),delayMs=Math.max(1,Math.round(base+jitter));if(emit("plan_ledger_cas_retry",{attempt,expectedHashPrefix:currentExpected.slice(0,8),delayMs}),await new Promise((resolve25)=>setTimeout(resolve25,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function loadPlanJsonOnly(directory){try{return await parsePlanJsonCached(directory)}catch(error49){warn(`Plan validation failed for .swarm/plan.json: ${error49 instanceof Error?error49.message:String(error49)}`)}return null}function compareTaskIds(a,b){let partsA=a.split(".").map((n)=>parseInt(n,10)),partsB=b.split(".").map((n)=>parseInt(n,10)),maxLen=Math.max(partsA.length,partsB.length);for(let i=0;i<maxLen;i++){let numA=partsA[i]??0,numB=partsB[i]??0;if(numA!==numB)return numA-numB}return 0}async function getLatestLedgerHash(directory){try{let events=await readLedgerEvents(directory);if(events.length===0)return"";return events[events.length-1].plan_hash_after}catch{return""}}async function surfaceLedgerStaleIfPersisted(directory,plan){let resolvedWorkspace=path45.resolve(directory);if(!ledgerStaleWorkspaces.has(resolvedWorkspace))return plan;try{let planHash=computePlanLedgerHash(plan),ledgerHash=await getLatestLedgerHash(directory);if(ledgerHash!==""&&planHash===ledgerHash)return ledgerStaleWorkspaces.delete(resolvedWorkspace),plan}catch{}if(plan._ledgerReplayStale=!0,typeof plan._ledgerReplayStaleReason!=="string"||plan._ledgerReplayStaleReason.length===0)plan._ledgerReplayStaleReason="plan.json still hash-mismatches the ledger after a startup ledger-replay failure (replay could not be applied and no critic-approved snapshot was available). Run /swarm reset-session if this persists.";return plan}async function parsePlanJsonCached(directory){let planJsonPath=path45.resolve(directory,".swarm","plan.json");return readCachedParsedFile(planJsonPath,PLAN_JSON_CACHE_NAMESPACE,()=>readSwarmFileAsync(directory,"plan.json"),(planJsonContent)=>{if(planJsonContent.includes("\x00")||planJsonContent.includes("�"))throw Error("Plan rejected: .swarm/plan.json contains null bytes or invalid encoding");let parsed=JSON.parse(planJsonContent);return PlanSchema.parse(parsed)})}function computePlanContentHash(plan){let content={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(compareTaskIds),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason})).sort((a,b)=>compareTaskIds(a.id,b.id))})).sort((a,b)=>a.id-b.id)},jsonString=JSON.stringify(content);return bunHash(jsonString).toString(36)}function extractPlanHashFromMarkdown(markdown){let match=markdown.match(/<!--\s*PLAN_HASH:\s*(\S+)\s*-->/);return match?match[1]:null}async function isPlanMdInSync(directory,plan,cache2){let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent===null)return!1;let expectedHash=computePlanContentHash(plan);if(extractPlanHashFromMarkdown(planMdContent)===expectedHash)return!0;let normalizedExpected=derivePlanMarkdown(plan).trim();if(planMdContent.trim()===normalizedExpected)return!0;return!1}async function regeneratePlanMarkdown(directory,plan){assertProjectRoot(directory);let swarmDir=path45.resolve(directory,".swarm"),contentHash=computePlanContentHash(plan),markdown=derivePlanMarkdown(plan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
563
|
+
${markdown}`,mdPath=path45.join(swarmDir,"plan.md"),mdTempPath=path45.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync12(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}async function loadPlan(directory,cache2){let planJsonContent=await readSwarmFileAsync(directory,"plan.json",cache2);if(planJsonContent!==null)if(planJsonContent.includes("\x00")||planJsonContent.includes("�"))warn("Plan rejected: .swarm/plan.json contains null bytes or invalid encoding");else try{let validated=await parsePlanJsonCached(directory);if(validated===null)warn("[loadPlan] plan.json disappeared during cached parse. Falling back to plan.md migration or ledger recovery.");else{if(!await isPlanMdInSync(directory,validated,cache2))try{await _internals35.regeneratePlanMarkdown(directory,validated)}catch(regenError){warn(`Failed to regenerate plan.md: ${regenError instanceof Error?regenError.message:String(regenError)}. Proceeding with plan.json only.`)}if(await ledgerExists(directory)){let planHash=computePlanLedgerHash(validated),ledgerHash=await getLatestLedgerHash(directory),resolvedWorkspace=path45.resolve(directory);if(!startupLedgerCheckedWorkspaces.has(resolvedWorkspace)){if(startupLedgerCheckedWorkspaces.add(resolvedWorkspace),ledgerHash!==""&&planHash!==ledgerHash){let currentPlanId=derivePlanId(validated),ledgerEvents=await readLedgerEvents(directory),firstEvent=ledgerEvents.length>0?ledgerEvents[0]:null;if(firstEvent&&firstEvent.plan_id!==currentPlanId)warn(`[loadPlan] Ledger identity mismatch (ledger: ${firstEvent.plan_id}, plan: ${currentPlanId}) — skipping ledger rebuild (migration detected). Use /swarm reset-session to reinitialize the ledger.`);else{warn("[loadPlan] plan.json is stale (hash mismatch with ledger) — rebuilding from ledger. If this recurs, run /swarm reset-session to clear stale session state.");try{let{plan:rebuilt,truncated}=await replayFromLedgerWithStatus(directory);if(truncated){let runtimeStale=validated;return runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason="Ledger truncated: a malformed line stopped replay before the tail, so the ledger could only be reconstructed up to the corruption. plan.json was PRESERVED (not rolled back to the prefix-only projection) and the corrupted suffix was quarantined to .swarm/plan-ledger.quarantine.*. Verify state, then run /swarm reset-session if this persists.",ledgerStaleWorkspaces.add(resolvedWorkspace),criticalWarn("[loadPlan] Ledger truncated (poison line detected) — preserving plan.json instead of rolling back to the prefix-only ledger projection. Durable post-poison events remain in plan.json. Corrupted suffix quarantined to .swarm/plan-ledger.quarantine.*. Run /swarm reset-session after verifying state if this persists."),runtimeStale}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"ledger_hash_mismatch_recovery"}),warn("[loadPlan] Rebuilt plan from ledger. Checkpoint available at .swarm/plan-export/SWARM_PLAN.md if it exists."),rebuilt}catch(replayError){try{let approved=await loadLastApprovedPlan(directory,currentPlanId);if(approved){await rebuildPlan(directory,approved.plan,{reason:"approved_snapshot_fallback"});try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;return warn(`[loadPlan] Ledger replay failed (${replayError instanceof Error?replayError.message:String(replayError)}) — recovered from critic-approved snapshot seq=${approved.seq} (approval phase=${approvedPhase??"unknown"}, timestamp=${approved.timestamp}). This may roll the plan back to an earlier phase — verify before continuing.`),approved.plan}}catch{}{let runtimeStale=validated;runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason=`Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error?replayError.message:String(replayError)}`,ledgerStaleWorkspaces.add(resolvedWorkspace)}warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error?replayError.message:String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`)}}}}else if(ledgerHash!==""&&planHash!==ledgerHash){if(process.env.DEBUG_SWARM)console.warn(`[loadPlan] Ledger hash mismatch during active session for ${resolvedWorkspace} — skipping rebuild (startup check already performed).`)}}if(validated.specHash){let staleResult=await isSpecStale(directory,validated);if(staleResult.stale){let runtimePlan=validated;if(runtimePlan._specStale=!0,runtimePlan._specStaleReason=staleResult.reason,!await isObligationPreserving(directory)){try{assertProjectRoot(directory);let diffInfo=computeSpecDiff(directory),specStalenessPath=path45.join(directory,".swarm","spec-staleness.json");await fsPromises4.writeFile(specStalenessPath,JSON.stringify({type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason,planTitle:validated.title,diff:diffInfo?.diff??null,changedSections:diffInfo?.changedSections??[]},null,2),"utf-8"),invalidateCachedArtifact(specStalenessPath)}catch{}try{assertProjectRoot(directory);let event={type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason??"unknown",planTitle:validated.title};appendCoreEventSync(directory,{...event})}catch{}}}}return await surfaceLedgerStaleIfPersisted(directory,validated)}}catch(error49){warn(`[loadPlan] plan.json validation failed: ${error49 instanceof Error?error49.message:String(error49)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);let rawPlanId=null;try{let rawParsed=JSON.parse(planJsonContent);if(typeof rawParsed?.swarm==="string"&&typeof rawParsed?.title==="string")rawPlanId=derivePlanId(rawParsed)}catch{}if(await ledgerExists(directory)){let ledgerEventsForCatch=await readLedgerEvents(directory),catchFirstEvent=ledgerEventsForCatch.length>0?ledgerEventsForCatch[0]:null;if(!(rawPlanId===null||catchFirstEvent===null||catchFirstEvent.plan_id===rawPlanId))warn(`[loadPlan] Ledger identity mismatch in validation-failure path (ledger: ${catchFirstEvent?.plan_id}, plan: ${rawPlanId}) — skipping ledger rebuild (migration detected).`);else if(catchFirstEvent!==null&&rawPlanId!==null){let rebuilt=await replayFromLedger(directory);if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"validation_failure_recovery"}),warn("[loadPlan] Rebuilt plan from ledger after validation failure. Projection was stale."),rebuilt}}let planMdContent2=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent2!==null){let migrated=migrateLegacyPlan(planMdContent2),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json");if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return migrated}}let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent!==null){let migrated=migrateLegacyPlan(planMdContent);return await savePlan(directory,migrated),migrated}if(await ledgerExists(directory)){let resolvedDir=path45.resolve(directory),existingMutex=recoveryMutexes.get(resolvedDir);if(existingMutex){await existingMutex;let postRecoveryPlan=await _internals35.loadPlanJsonOnly(directory);if(postRecoveryPlan)return postRecoveryPlan}let resolveRecovery,mutex=new Promise((r)=>{resolveRecovery=r});recoveryMutexes.set(resolvedDir,mutex);try{let rebuilt=await replayFromLedger(directory);if(rebuilt){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,rebuilt,"load_plan_rebuild_from_ledger","rebuild plan from ledger replay");if(removedCount>0)rebuilt._midLoadRemovals={count:removedCount,source:"load_plan_rebuild_from_ledger"};return rebuilt}try{let anchorEvents=await readLedgerEvents(directory);if(anchorEvents.length===0)return warn("[loadPlan] Ledger present but no events readable — refusing approved-snapshot recovery (cannot verify plan identity)."),null;let expectedPlanId=anchorEvents[0].plan_id,approved=await loadLastApprovedPlan(directory,expectedPlanId);if(approved){let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;warn(`[loadPlan] Ledger replay returned no plan — recovered from critic-approved snapshot seq=${approved.seq} timestamp=${approved.timestamp} (approval phase=${approvedPhase??"unknown"}). This may roll the plan back to an earlier phase — verify before continuing.`);let{removedCount:snapshotRemovedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot");if(snapshotRemovedCount>0)approved.plan._midLoadRemovals={count:snapshotRemovedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval})}catch(healError){warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return approved.plan}}catch(recoveryError){warn(`[loadPlan] Approved-snapshot recovery failed: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`)}}finally{resolveRecovery(),recoveryMutexes.delete(resolvedDir)}}return null}async function savePlanWithAutoAcknowledgedRemovals(directory,plan,source,reason,options){let existing=await _internals35.loadPlanJsonOnly(directory),newIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)newIds.add(task.id);let removedIds=[];if(existing){for(let phase of existing.phases)for(let task of phase.tasks)if(!newIds.has(task.id))removedIds.push(task.id)}return await savePlan(directory,plan,{...options??{},acknowledged_removals:{ids:removedIds,reason,source}}),{removedCount:removedIds.length}}async function savePlan(directory,plan,options){if(directory===null||directory===void 0||typeof directory!=="string"||directory.trim().length===0)throw Error("Invalid directory: directory must be a non-empty string");if(assertProjectRoot(directory),!options?.planLockAlreadyHeld){let lockResult=await tryAcquireLock(directory,"plan.json","plan-manager",`save-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{await savePlan(directory,plan,{...options,planLockAlreadyHeld:!0});return}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}let validated=PlanSchema.parse(plan),requestedForStaleProjectionReconcile=options?.staleProjectionReconcile!==void 0?PlanSchema.parse(plan):null;if(requestedForStaleProjectionReconcile)derivePhaseStatusesInPlace(requestedForStaleProjectionReconcile);if(options?.preserveCompletedStatuses!==!1)try{let currentPlan2=await _internals35.loadPlanJsonOnly(directory);if(currentPlan2){let completedTaskIds=new Set;for(let phase of currentPlan2.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.add(task.id);if(completedTaskIds.size>0){for(let phase of validated.phases)for(let task of phase.tasks)if(completedTaskIds.has(task.id)&&task.status!=="completed")task.status="completed"}}}catch{}derivePhaseStatusesInPlace(validated);let currentPlan=await _internals35.loadPlanJsonOnly(directory),planId=derivePlanId(validated),planHashForInit=computePlanLedgerHash(validated);if(!await ledgerExists(directory))try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated)}catch(initErr){let msg=initErr instanceof Error?initErr.message:String(initErr);if(!/already initialized/i.test(msg))throw initErr}else{let existingEvents=await readLedgerEvents(directory);if(existingEvents.length>0&&existingEvents[0].plan_id!==planId){let swarmDir2=path45.resolve(directory,".swarm"),oldLedgerPath=path45.join(swarmDir2,"plan-ledger.jsonl"),oldLedgerBackupPath=path45.join(swarmDir2,`plan-ledger.backup-${Date.now()}-${Math.floor(Math.random()*1e9)}.jsonl`),backupExists=!1;if(existsSync24(oldLedgerPath))try{options?.preCommitCheck?.(),renameSync12(oldLedgerPath,oldLedgerBackupPath),backupExists=!0}catch(renameErr){throw Error(`[savePlan] Cannot reinitialize ledger: could not move old ledger aside (rename failed: ${renameErr instanceof Error?renameErr.message:String(renameErr)}). The existing ledger has plan_id="${existingEvents[0].plan_id}" which does not match the current plan="${planId}". To proceed, close any programs that may have the ledger file open, or run /swarm reset-session to clear the ledger.`)}let initSucceeded=!1;if(backupExists)try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated),initSucceeded=!0}catch(initErr){if(String(initErr).includes("already initialized"))try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}else{if(existsSync24(oldLedgerBackupPath))try{renameSync12(oldLedgerBackupPath,oldLedgerPath)}catch{copyFileSync(oldLedgerBackupPath,oldLedgerPath);try{unlinkSync12(oldLedgerBackupPath)}catch{}}throw initErr}}if(initSucceeded&&backupExists){let archivePath=path45.join(swarmDir2,`plan-ledger.archived-${Date.now()}-${Math.floor(Math.random()*1e9)}.jsonl`);try{renameSync12(oldLedgerBackupPath,archivePath),warn(`[savePlan] Ledger identity mismatch (was "${existingEvents[0].plan_id}", now "${planId}") — archived old ledger to ${archivePath} and reinitializing.`)}catch(renameErr){warn(`[savePlan] Could not archive old ledger (rename failed: ${renameErr instanceof Error?renameErr.message:String(renameErr)}). Old ledger may still exist at ${oldLedgerBackupPath}.`);try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}}}else if(!initSucceeded&&backupExists)try{if(existsSync24(oldLedgerBackupPath))unlinkSync12(oldLedgerBackupPath)}catch{}let MAX_ARCHIVED_SIBLINGS=5;try{let archivedSiblings=readdirSync7(swarmDir2).filter((f)=>f.startsWith("plan-ledger.archived-")&&f.endsWith(".jsonl")).sort();if(archivedSiblings.length>MAX_ARCHIVED_SIBLINGS){let toRemove=archivedSiblings.slice(0,archivedSiblings.length-MAX_ARCHIVED_SIBLINGS);for(let file2 of toRemove)try{unlinkSync12(path45.join(swarmDir2,file2))}catch{}}}catch{}}}if(options?.staleProjectionReconcile){if(!currentPlan)throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: no current plan.json projection exists.");let comparableCurrent=PlanSchema.parse(currentPlan);if(derivePhaseStatusesInPlace(comparableCurrent),JSON.stringify(comparableCurrent)!==JSON.stringify(requestedForStaleProjectionReconcile))throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: manager rejected content that is not the exact unchanged plan.json projection.");let events=await readLedgerEvents(directory),tail=events[events.length-1],expected=options.staleProjectionReconcile;if(!tail||tail.seq!==expected.expectedSeq||tail.plan_hash_after!==expected.expectedLedgerHash||events[0]?.plan_id!==planId)throw new PlanConcurrentModificationError("RECONCILE_LEDGER_PROJECTION_STALE: the ledger identity or tail changed before the recovery snapshot could be appended.");try{if((await readLedgerEventsWithIntegrity(directory)).truncated)await replaceTruncatedLedgerWithRecoveryRoot(directory,validated,{seq:expected.expectedSeq,ledgerHash:expected.expectedLedgerHash});else await takeSnapshotEvent(directory,validated,{planHashAfter:computePlanLedgerHash(validated),source:"save_plan_stale_projection_reconcile",expectedSeq:expected.expectedSeq,expectedLedgerHash:expected.expectedLedgerHash})}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`RECONCILE_LEDGER_PROJECTION_STALE: ${error49.message}`);throw error49}}let currentHash=computeCurrentPlanHash(directory),hashAfter=computePlanLedgerHash(validated);if(currentPlan){let oldTaskMap=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldTaskMap.set(task.id,{phase:task.phase,status:task.status});let newTaskIds=new Set;for(let phase of validated.phases)for(let task of phase.tasks)newTaskIds.add(task.id);let missingTasks=[];for(let[id,info]of oldTaskMap.entries())if(!newTaskIds.has(id))missingTasks.push({id,phase:info.phase,status:info.status});let ack=options?.acknowledged_removals;if(missingTasks.length>0){if(!ack)throw new PlanTaskRemovalNotAcknowledgedError(missingTasks);if(typeof ack.reason!=="string"||ack.reason.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.reason must be a non-empty string.");if(typeof ack.source!=="string"||ack.source.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.source must be a non-empty string.");let ackSet=new Set(ack.ids),missingIdsSet=new Set(missingTasks.map((t)=>t.id)),unacked=missingTasks.filter((t)=>!ackSet.has(t.id));if(unacked.length>0)throw new PlanTaskRemovalNotAcknowledgedError(unacked);for(let id of ack.ids)if(!missingIdsSet.has(id))throw Error(`PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals contains "${id}" but that task is not missing from the plan.`);try{for(let missing of missingTasks){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_removed",task_id:missing.id,phase_id:missing.phase,from_status:missing.status,source:ack.source,payload:{reason:ack.reason,source:ack.source}},capturedTaskId=missing.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals35.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases)if(p.tasks.some((x)=>x.id===capturedTaskId))return!0;return!1}})}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}try{for(let phase of validated.phases)for(let task of phase.tasks){let oldTask=oldTaskMap.get(task.id);if(oldTask&&oldTask.status!==task.status){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_status_changed",task_id:task.id,phase_id:phase.id,from_status:oldTask.status,to_status:task.status,source:"savePlan"},capturedFromStatus=oldTask.status,capturedTaskId=task.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,verifyValid:async()=>{let onDisk=await _internals35.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases){let t=p.tasks.find((x)=>x.id===capturedTaskId);if(t)return t.status===capturedFromStatus}return!1}})}}}catch(error49){if(error49 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error49.message}. Please retry the operation.`);throw error49}}let ledgerStatusTaskIds=collectLedgerStatusTaskIds(await readLedgerEvents(directory)),replayedBeforeProjection=await replayFromLedger(directory),projectionCandidate=replayedBeforeProjection?mergeStatusesTakingPrecedence(validated,replayedBeforeProjection,ledgerStatusTaskIds):validated;if(replayedBeforeProjection&&computePlanLedgerHash(replayedBeforeProjection)!==computePlanLedgerHash(projectionCandidate))options?.preCommitCheck?.(),await takeSnapshotEvent(directory,projectionCandidate,{planHashAfter:computePlanLedgerHash(projectionCandidate),source:"savePlan_structural_projection"});let projectedPlan=projectionCandidate,SNAPSHOT_INTERVAL=50,latestSeq=await getLatestLedgerSeq(directory);if(!options?.preCommitCheck&&latestSeq>0&&latestSeq%SNAPSHOT_INTERVAL===0)await takeSnapshotWithRetry(directory,projectedPlan,{planHashAfter:computePlanLedgerHash(projectedPlan),source:"savePlan_manager"});let swarmDir=path45.resolve(directory,".swarm"),planPath=path45.join(swarmDir,"plan.json"),tempPath=path45.join(swarmDir,`plan.json.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(tempPath,JSON.stringify(projectedPlan,null,2)),options?.preCommitCheck?.(),renameSync12(tempPath,planPath)}finally{try{unlinkSync12(tempPath)}catch{}}invalidateCachedArtifact(planPath);try{let markerPath=path45.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:projectedPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(projectedPlan),markdown=derivePlanMarkdown(projectedPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
564
564
|
${markdown}`,mdPath=path45.join(swarmDir,"plan.md"),mdTempPath=path45.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),renameSync12(mdTempPath,mdPath)}finally{try{unlinkSync12(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}catch(mdError){let message=mdError instanceof Error?mdError.message:String(mdError);warn(`[savePlan] plan.md write failed (non-fatal, plan.json is authoritative): ${message}`);try{emit("plan_md_write_failed",{directory,error:message,timestamp:new Date().toISOString()})}catch{}}try{let markerPath=path45.join(swarmDir,".plan-write-marker"),tasksCount=projectedPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}if(currentPlan)try{let oldIdentityHash=derivePlanIdentityHash(currentPlan),newIdentityHash=derivePlanIdentityHash(projectedPlan);if(oldIdentityHash===newIdentityHash){let oldStatuses=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldStatuses.set(task.id,task.status);let newStatuses=new Map;for(let phase of projectedPlan.phases)for(let task of phase.tasks)newStatuses.set(task.id,task.status);for(let[taskId,oldStatus]of oldStatuses){let newStatus=newStatuses.get(taskId);if(oldStatus==="completed"&&newStatus!=="completed")advanceTaskCheckpointReceiptGeneration(directory,oldIdentityHash,taskId)}for(let[taskId,newStatus]of newStatuses)if(newStatus==="completed"&&oldStatuses.get(taskId)!=="completed")repairTaskCheckpointReceiptForCompletion(directory,newIdentityHash,taskId)}}catch(receiptError){warn(`[savePlan] task checkpoint receipt lifecycle sync failed (plan remains authoritative): ${receiptError instanceof Error?receiptError.message:String(receiptError)}`)}}async function rebuildPlan(directory,plan,options){assertProjectRoot(directory);let targetPlan=plan??await replayFromLedger(directory);if(!targetPlan)return null;let swarmDir=path45.join(directory,".swarm"),planPath=path45.join(swarmDir,"plan.json"),mdPath=path45.join(swarmDir,"plan.md");mkdirSync20(swarmDir,{recursive:!0});let tempPlanPath=path45.join(swarmDir,`plan.json.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);{let fd=openSync7(tempPlanPath,"w");try{writeFileSync13(fd,JSON.stringify(targetPlan,null,2),"utf8"),fsyncSync3(fd)}finally{closeSync7(fd)}}renameSync12(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path45.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let contentHash=computePlanContentHash(targetPlan),markdown=derivePlanMarkdown(targetPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
565
|
-
${markdown}`,tempMdPath=path45.join(swarmDir,`plan.md.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempMdPath,markdownWithHash),renameSync12(tempMdPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{let markerPath=path45.join(swarmDir,".plan-write-marker"),tasksCount=targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}}try{let planId=derivePlanId(targetPlan),planHashAfter=
|
|
565
|
+
${markdown}`,tempMdPath=path45.join(swarmDir,`plan.md.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempMdPath,markdownWithHash),renameSync12(tempMdPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{let markerPath=path45.join(swarmDir,".plan-write-marker"),tasksCount=targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}}try{let planId=derivePlanId(targetPlan),planHashAfter=computePlanLedgerHash(targetPlan);await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"rebuildPlan",plan_id:planId,payload:{reason:options?.reason??"ledger_replay_recovery",phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0)}},{planHashAfter})}catch{}return targetPlan}async function closePlanTerminalState(directory,plan,options){assertProjectRoot(directory);let planId=derivePlanId(plan),validated=PlanSchema.parse(plan),hashAfter=computePlanLedgerHash(validated);for(let taskId of options.closedTaskIds){let taskPhaseId;for(let phase of validated.phases)if(phase.tasks.some((t)=>t.id===taskId)){taskPhaseId=phase.id;break}let fromStatus=options.originalStatuses?.get(taskId)??"in_progress";await appendLedgerEvent(directory,{plan_id:planId,event_type:"task_status_changed",task_id:taskId,phase_id:taskPhaseId,from_status:fromStatus,to_status:"closed",source:"close_terminal"},{planHashAfter:hashAfter})}for(let phaseId of options.closedPhaseIds)await appendLedgerEvent(directory,{plan_id:planId,event_type:"phase_completed",phase_id:phaseId,source:"close_terminal"},{planHashAfter:hashAfter});await takeSnapshotEvent(directory,validated,{planHashAfter:hashAfter,source:"close_terminal"});let swarmDir=path45.join(directory,".swarm"),planPath=path45.join(swarmDir,"plan.json"),tempPlanPath=path45.join(swarmDir,`plan.json.close.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempPlanPath,JSON.stringify(validated,null,2)),renameSync12(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path45.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager_close",timestamp:new Date().toISOString(),phases_count:validated.phases.length,tasks_count:validated.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let mdPath=path45.join(swarmDir,"plan.md"),contentHash=computePlanContentHash(validated),markdown=derivePlanMarkdown(validated),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
566
566
|
${markdown}`,mdTempPath=path45.join(swarmDir,`plan.md.close.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(mdTempPath,markdownWithHash),renameSync12(mdTempPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{let markerPath=path45.join(swarmDir,".plan-write-marker"),tasksCount=validated.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager_close",timestamp:new Date().toISOString(),phases_count:validated.phases.length,tasks_count:tasksCount,in_progress:!1});await bunWrite(markerPath,marker)}catch{}}}async function updateTaskStatus(directory,taskId,status,options){assertProjectRoot(directory);let derivePhaseStatusFromTasks=(tasks)=>{if(tasks.length>0&&tasks.every((task)=>task.status==="completed"))return"complete";if(tasks.some((task)=>task.status==="in_progress"))return"in_progress";if(tasks.some((task)=>task.status==="blocked"))return"blocked";return"pending"};{let currentPlan=await _internals35.loadPlanJsonOnly(directory);if(currentPlan){let currentTask=currentPlan.phases.flatMap((p)=>p.tasks).find((t)=>t.id===taskId),settled=currentTask&¤tTask.status!=="pending"&¤tTask.status!=="in_progress",auditedRepair=status==="in_progress"&&options?.force===!0;if(settled&&status!==currentTask.status&&!auditedRepair&&options?.terminalReconciliation!==!0)return warn(`[updateTaskStatus] refusing backward transition of settled task ${taskId} (${currentTask.status}) to ${status} without audited repair`),currentPlan}}let MAX_OUTER_RETRIES=1;for(let attempt=0;attempt<=MAX_OUTER_RETRIES;attempt++){let plan=await _internals35.loadPlan(directory);if(plan===null)throw Error(`Plan not found in directory: ${directory}`);let taskFound=!1,updatedPhases=plan.phases.map((phase)=>{let updatedTasks=phase.tasks.map((task)=>{if(task.id===taskId)return taskFound=!0,{...task,status};return task});return{...phase,status:derivePhaseStatusFromTasks(updatedTasks),tasks:updatedTasks}});if(!taskFound)throw Error(`Task not found: ${taskId}`);let updatedPlan={...plan,phases:updatedPhases};try{if(await savePlan(directory,updatedPlan,{preserveCompletedStatuses:!1,planLockAlreadyHeld:options?.planLockAlreadyHeld}),status==="completed"||status==="blocked"){let recordedTask=updatedPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);try{await _internals35.recordTaskAttempt(directory,{taskId,agent:"plan-status",outcome:status==="completed"?"pass":"fail",failureReason:status==="blocked"?recordedTask?.blocked_reason??"task marked blocked (no blocked_reason recorded)":void 0,fileTargets:recordedTask?.files_touched??[]})}catch(err){warn(`[plan/manager] run-memory record for ${taskId} failed: ${err instanceof Error?err.message:String(err)}`)}}if(status==="completed"&&_internals35.isGitRepo(directory)&&_internals35.isEpicModeActiveForProject(directory)){let mergeFailure=_internals35.getWorktreeMergeFailure(taskId);if(mergeFailure)return criticalWarn(`[plan/manager] Rule 2 auto-commit SKIPPED for ${taskId}: worktree merge-back ${mergeFailure.outcome} at stage '${mergeFailure.stage}'. The task's changes are NOT in the main tree, so no completion marker is written (Rule 3 must not treat this task as satisfied). Resolve the preserved worktree, then re-run the task. Detail: ${mergeFailure.message}`),updatedPlan;try{let taskDescription;for(let phase of updatedPlan.phases){let found=phase.tasks.find((t)=>t.id===taskId);if(found){taskDescription=found.description;break}}let canonicalScope=_internals35.readTaskScopes(directory,taskId);await _internals35.commitTaskCompletion(directory,taskId,taskDescription,canonicalScope??void 0)}catch(commitErr){criticalWarn(`[plan/manager] Rule 2 auto-commit for ${taskId} threw (non-fatal): ${commitErr instanceof Error?commitErr.message:String(commitErr)}`)}}return updatedPlan}catch(error49){if(error49 instanceof PlanConcurrentModificationError&&attempt<MAX_OUTER_RETRIES)continue;throw error49}}throw Error("updateTaskStatus: unexpected loop exit")}function derivePlanMarkdown(plan){let statusMap={pending:"PENDING",in_progress:"IN PROGRESS",complete:"COMPLETE",completed:"COMPLETE",blocked:"BLOCKED",closed:"CLOSED"},now=new Date().toISOString(),currentPhase=plan.current_phase??1,phaseStatus=statusMap[plan.phases[currentPhase-1]?.status]||"PENDING",markdown=`# ${plan.title}
|
|
567
567
|
Swarm: ${plan.swarm}
|
|
568
568
|
Phase: ${currentPhase} [${phaseStatus}] | Updated: ${now}
|
|
@@ -3486,7 +3486,7 @@ ${JSON_CLOSE_TAG}`,body=JSON.stringify(payload,null,2);while(Buffer.byteLength(w
|
|
|
3486
3486
|
`);if(!ctx.reviewModelDispatcher)return"Review runtime unavailable: no ReviewModelDispatcher is bound. Run `/swarm review` from an active plugin session; the standalone CLI cannot dispatch isolated review-model sessions.";let reviewerAgent,validatorAgent;try{let names=resolveReviewAgentNames(Object.keys(ctx.agents),ctx.activeAgentName);reviewerAgent=names.reviewer,validatorAgent=names.validator}catch(error93){return`Review runtime unavailable: ${error93 instanceof Error?error93.message:String(error93)}`}if(!Object.hasOwn(ctx.agents,reviewerAgent))return"Review runtime unavailable: no generated reviewer agent is registered for this plugin session.";let config3=ctx.autoReviewConfig??resolveAutoReviewConfig({});if((config3.validate_findings||config3.final_review.mode==="gate")&&!Object.hasOwn(ctx.agents,validatorAgent))return"Review runtime unavailable: finding validation is enabled but no generated critic_finding_validator agent is registered.";let reviewerModel,reviewerFallbackModels=[],validatorModel,validatorFallbackModels=[];try{reviewerModel=config3.final_review.model?parseModelString2(config3.final_review.model):void 0,reviewerFallbackModels=resolveReviewFallbackModels(reviewerAgent,ctx.reviewAgentModelRegistry),validatorModel=config3.validation_model?parseModelString2(config3.validation_model):void 0,validatorFallbackModels=resolveReviewFallbackModels(validatorAgent,ctx.reviewAgentModelRegistry)}catch(error93){return`Review configuration error: ${error93 instanceof Error?error93.message:String(error93)}`}let result=await _internals169.runReviewEngine({directory:ctx.directory,sessionID:ctx.sessionID,trigger:"manual",selector:parsed.selector,config:config3,dispatcher:ctx.reviewModelDispatcher,reviewerAgent,validatorAgent,reviewerModel,reviewerFallbackModels,validatorModel,validatorFallbackModels}),evidence2=_internals169.readEvidence(result.evidencePath,ctx.directory);return parsed.json?renderJson(result,evidence2,parsed.selector):renderHuman(result,evidence2,parsed.selector)}var MAX_EVIDENCE_BYTES=524288,MAX_JSON_WRAPPER_BYTES=65536,MAX_DISPLAY_TEXT=500,MAX_SCOPE_WARNINGS=20,MAX_SCOPE_FILES2=25,JSON_OPEN_TAG="[SWARM_REVIEW_JSON]",JSON_CLOSE_TAG="[/SWARM_REVIEW_JSON]",SEVERITY_RANK,_internals169;var init_review=__esm(()=>{init_schema();init_diff_source();init_engine2();init_evidence2();init_runtime2();init_model_dispatch_fallback();SEVERITY_RANK={critical:0,high:1,medium:2,low:3,info:4};_internals169={runReviewEngine,readEvidence}});import*as fs112 from"node:fs";import*as path212 from"node:path";function safeParseToolJson(result){try{let jsonStr=typeof result==="string"?result:result.output;return JSON.parse(jsonStr)}catch{return null}}async function listGitCheckpoints(directory){try{let result=await checkpoint.execute({action:"list"},{directory}),parsed=safeParseToolJson(result);if(!parsed)return null;if(parsed.success!==!0||!Array.isArray(parsed.checkpoints))return null;return parsed.checkpoints}catch{return null}}function formatGitCheckpointList(checkpoints){if(checkpoints.length===0)return"No checkpoints found. Create one with `/swarm checkpoint save <label>`";return["## Available Checkpoints","",...checkpoints.map((c,index)=>`- ${index+1}. "${c.label}" - ${new Date(c.timestamp).toLocaleString()} (${c.sha.slice(0,12)})`),"","Run `/swarm rollback <label-or-number>` to restore to a checkpoint."].join(`
|
|
3487
3487
|
`)}function resolveGitCheckpoint(checkpoints,selector){let index=Number.parseInt(selector,10);if(/^\d+$/.test(selector)&&index>=1&&index<=checkpoints.length)return checkpoints[index-1]??null;return checkpoints.find((c)=>c.label===selector)??null}async function restoreGitCheckpoint(directory,selected){let result=await checkpoint.execute({action:"restore",label:selected.label},{directory}),parsed=safeParseToolJson(result);if(!parsed)return`Error: Failed to parse checkpoint response for "${selected.label}"`;if(parsed.success!==!0)return`Error: ${parsed.error||`Failed to restore checkpoint "${selected.label}"`}`;let rollbackEvent={type:"rollback",label:selected.label,sha:selected.sha,timestamp:new Date().toISOString(),source:"checkpoints.json"};try{appendCoreEventSync(directory,rollbackEvent)}catch(error93){log("Failed to write rollback event:",error93 instanceof Error?error93.message:String(error93))}return`Rolled back to checkpoint "${selected.label}" (${selected.sha.slice(0,12)})`}async function handleRollbackCommand(directory,args2){let phaseArg=args2[0];if(!phaseArg){let manifestPath3=validateSwarmPath(directory,"checkpoints/manifest.json");if(!fs112.existsSync(manifestPath3)){let gitCheckpoints=await listGitCheckpoints(directory);if(gitCheckpoints)return formatGitCheckpointList(gitCheckpoints);return"No checkpoints found. Use `/swarm checkpoint save <label>` to create checkpoints."}let manifest2;try{manifest2=JSON.parse(fs112.readFileSync(manifestPath3,"utf-8"))}catch{return"Error: Checkpoint manifest is corrupted. Delete .swarm/checkpoints/manifest.json and re-checkpoint."}let checkpoints=manifest2.checkpoints||[];if(checkpoints.length===0)return"No checkpoints found in manifest.";return["## Available Checkpoints","",...checkpoints.map((c)=>`- Phase ${c.phase}: ${c.label||"no label"} (${new Date(c.timestamp).toLocaleString()})`),"","Run `/swarm rollback <phase>` to restore to a checkpoint."].join(`
|
|
3488
3488
|
`)}let targetPhase=parseInt(phaseArg,10);if(Number.isNaN(targetPhase)||targetPhase<1){let gitCheckpoints=await listGitCheckpoints(directory);if(!gitCheckpoints)return"Error: Phase number must be a positive integer.";let selected=resolveGitCheckpoint(gitCheckpoints,phaseArg);if(!selected)return`Error: Checkpoint "${phaseArg}" not found. Available checkpoints: ${gitCheckpoints.map((c)=>`"${c.label}"`).join(", ")||"none"}`;return restoreGitCheckpoint(directory,selected)}let manifestPath2=validateSwarmPath(directory,"checkpoints/manifest.json");if(!fs112.existsSync(manifestPath2)){let gitCheckpoints=await listGitCheckpoints(directory);if(!gitCheckpoints)return`Error: No checkpoints found. Cannot rollback to phase ${targetPhase}.`;let selected=resolveGitCheckpoint(gitCheckpoints,phaseArg);if(!selected)return`Error: Checkpoint ${phaseArg} not found. Available checkpoints: ${gitCheckpoints.map((c,index)=>`${index+1}="${c.label}"`).join(", ")||"none"}`;return restoreGitCheckpoint(directory,selected)}let manifest;try{manifest=JSON.parse(fs112.readFileSync(manifestPath2,"utf-8"))}catch{return"Error: Checkpoint manifest is corrupted. Delete .swarm/checkpoints/manifest.json and re-checkpoint."}let checkpoint2=manifest.checkpoints?.find((c)=>c.phase===targetPhase);if(!checkpoint2){let available=manifest.checkpoints?.map((c)=>c.phase).join(", ")||"none";return`Error: Checkpoint for phase ${targetPhase} not found. Available phases: ${available}`}let checkpointDir=validateSwarmPath(directory,`checkpoints/phase-${targetPhase}`);if(!fs112.existsSync(checkpointDir))return`Error: Checkpoint directory for phase ${targetPhase} does not exist.`;let checkpointFiles=fs112.readdirSync(checkpointDir);if(checkpointFiles.length===0)return`Error: Checkpoint for phase ${targetPhase} is empty. Cannot rollback.`;let swarmDir=path212.dirname(validateSwarmPath(directory,".keep")),EXCLUDE_FILES=new Set(["plan-ledger.jsonl","plan-ledger.quarantine"]),successes=[],failures=[],warnings=[];for(let file3 of checkpointFiles){if(EXCLUDE_FILES.has(file3)||file3.startsWith("plan-ledger.archived-"))continue;let src=path212.join(checkpointDir,file3),dest=path212.join(swarmDir,file3);try{fs112.cpSync(src,dest,{recursive:!0,force:!0}),successes.push(file3)}catch(error93){failures.push({file:file3,error:error93.message})}}if(resetSwarmArtifactCache(),failures.length>0)return[`Rollback partially completed. Successfully restored ${successes.length} files.`,`Failed on ${failures.length} files:`,...failures.map((f)=>` - ${f.file}: ${f.error}`),"","Some files could not be restored. The .swarm/ directory may be in an inconsistent state.","Check permissions and disk space, then retry the rollback."].join(`
|
|
3489
|
-
`);let existingLedgerPath=path212.join(swarmDir,"plan-ledger.jsonl"),ledgerDeletionFailed=!1;if(fs112.existsSync(existingLedgerPath))try{fs112.unlinkSync(existingLedgerPath)}catch(err){ledgerDeletionFailed=!0;let errMsg=err instanceof Error?err.message:String(err);warnings.push(`⚠️ Warning: Could not delete stale ledger (${errMsg}). The ledger may be inconsistent with the restored plan. Run /swarm reset-session to clean up session state.`)}if(!ledgerDeletionFailed)try{let planJsonPath=path212.join(swarmDir,"plan.json");if(fs112.existsSync(planJsonPath)){let planRaw=fs112.readFileSync(planJsonPath,"utf-8"),plan=PlanSchema.parse(JSON.parse(planRaw)),planId=derivePlanId(plan),planHash=
|
|
3489
|
+
`);let existingLedgerPath=path212.join(swarmDir,"plan-ledger.jsonl"),ledgerDeletionFailed=!1;if(fs112.existsSync(existingLedgerPath))try{fs112.unlinkSync(existingLedgerPath)}catch(err){ledgerDeletionFailed=!0;let errMsg=err instanceof Error?err.message:String(err);warnings.push(`⚠️ Warning: Could not delete stale ledger (${errMsg}). The ledger may be inconsistent with the restored plan. Run /swarm reset-session to clean up session state.`)}if(!ledgerDeletionFailed)try{let planJsonPath=path212.join(swarmDir,"plan.json");if(fs112.existsSync(planJsonPath)){let planRaw=fs112.readFileSync(planJsonPath,"utf-8"),plan=PlanSchema.parse(JSON.parse(planRaw)),planId=derivePlanId(plan),planHash=computePlanLedgerHash(plan);await initLedger(directory,planId,planHash,plan),await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"rollback",plan_id:planId})}}catch(initError){return[`Rollback restored files but failed to initialize ledger: ${initError instanceof Error?initError.message:String(initError)}`,"The .swarm/plan.json has been restored but the ledger may be out of sync.","Run /swarm reset-session to reinitialize the ledger."].join(`
|
|
3490
3490
|
`)}let rollbackEvent={type:"rollback",phase:targetPhase,label:checkpoint2.label||"",timestamp:new Date().toISOString()};try{appendCoreEventSync(directory,rollbackEvent)}catch(error93){log("Failed to write rollback event:",error93 instanceof Error?error93.message:String(error93))}if(warnings.length>0)return[...warnings,"",`Rolled back to phase ${targetPhase}: ${checkpoint2.label||"no label"}`].join(`
|
|
3491
3491
|
`);return`Rolled back to phase ${targetPhase}: ${checkpoint2.label||"no label"}`}var init_rollback=__esm(()=>{init_plan_schema();init_core_events();init_utils2();init_ledger();init_utils3();init_checkpoint();init_logger();init_swarm_artifact_cache()});import*as fs113 from"node:fs";import*as path213 from"node:path";function allowedMutationsFor(source){return source==="swarm"?["create","refine","archive"]:["none (read-only input; refine in the source tool)"]}function isUnsafeId(value){return value.includes("/")||value.includes("\\")||value.includes("..")||value.includes("[")||value.includes("]")||containsControlChars(value)}function parseArgs11(args2){let parsed={json:!1,dryRun:!1,overwrite:!1};for(let i=0;i<args2.length;i++){let token=args2[i];if(token==="--json")parsed.json=!0;else if(token==="--dry-run")parsed.dryRun=!0;else if(token==="--overwrite")parsed.overwrite=!0;else if(token==="--change"){if(i+1>=args2.length||args2[i+1].startsWith("--"))return{...parsed,error:"--change requires a value"};let value=args2[++i];if(isUnsafeId(value))return{...parsed,error:"--change must be a single OpenSpec change id with no path separators, traversal, brackets, or control characters"};parsed.changeId=value}else if(token==="--source"){if(i+1>=args2.length||args2[i+1].startsWith("--"))return{...parsed,error:"--source requires a value"};let value=args2[++i];if(value!=="swarm"&&value!=="openspec"&&value!=="speckit")return{...parsed,error:`--source must be one of: swarm | openspec | speckit; got "${value}"`};parsed.source=value}else if(token==="--feature"){if(i+1>=args2.length||args2[i+1].startsWith("--"))return{...parsed,error:"--feature requires a value"};let value=args2[++i];if(isUnsafeId(value))return{...parsed,error:"--feature must be a single Spec-Kit feature directory name with no path separators, traversal, brackets, or control characters"};parsed.feature=value}else return{...parsed,error:`Unknown flag "${token}"`}}return parsed}function formatList(items){return items.length>0?items.map((item)=>`- ${item}`).join(`
|
|
3492
3492
|
`):"- none"}function formatSpeckitError(resolution){switch(resolution.kind){case"empty":return"Spec-Kit layout detected (.specify/ marker present) but no feature directories found under specs/.";case"ambiguous":return[`Multiple Spec-Kit features detected: ${resolution.features.join(", ")}.`,"Use --feature <id> to select one."].join(`
|
|
@@ -7043,7 +7043,7 @@ Return a JSON array where each element has:
|
|
|
7043
7043
|
- Generate 3-5 mutations per function
|
|
7044
7044
|
|
|
7045
7045
|
Return ONLY a valid JSON array. No markdown, no code fences, no explanation. Start your response with [ and end with ].`,startedAt=Date.now(),promptResult=(await dispatchWithModelFallback({dispatch:async(_model,context)=>await withTimeoutSignal((signal2)=>client.session.prompt({path:{id:ephemeralSessionId},body:{agent:void 0,tools:{write:!1,edit:!1,patch:!1},parts:[{type:"text",text:promptText}]},signal:signal2}),context.remainingMs??MUTATION_GENERATOR_TOTAL_TIMEOUT_MS,Error(`generateMutants prompt timed out after ${context.remainingMs??MUTATION_GENERATOR_TOTAL_TIMEOUT_MS}ms`)),classify:(error93)=>isTransientProviderError(error93 instanceof Error?error93.message:String(error93))?"transient":"permanent",maxTransientRetriesPerModel:MUTATION_GENERATOR_MAX_RETRIES,backoffMs:()=>0,maxAttempts:MUTATION_GENERATOR_MAX_RETRIES+1,deadlineAtMs:startedAt+MUTATION_GENERATOR_TOTAL_TIMEOUT_MS})).result;if(!promptResult.data)return log(`[generateMutants] LLM prompt failed: ${JSON.stringify(promptResult.error)}; returning empty patch set`),[];let rawText=promptResult.data.parts.filter((p)=>p.type==="text").map((p)=>p.text).join(`
|
|
7046
|
-
`),parsed;try{parsed=JSON.parse(extractJsonArray(rawText))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93),hint=msg.includes("EOF")||msg.includes("Unexpected end")?" (response appears truncated — LLM may have hit an output token limit)":"";return log(`[generateMutants] Failed to parse LLM response as MutationPatch[]: ${msg}${hint}; returning empty patch set`),[]}if(!Array.isArray(parsed)||parsed.length===0)return[];let patches=[];for(let item of parsed){if(typeof item!=="object"||item===null||typeof item.filePath!=="string"||typeof item.functionName!=="string"||typeof item.mutationType!=="string"||typeof item.patch!=="string")continue;let mutationType=item.mutationType,fileSlug=slugify3(item.filePath),fnSlug=slugify3(item.functionName),typeSlug=slugify3(mutationType),idStr=typeof item.id==="string"?item.id:"",id=idStr.startsWith("mut-")?idStr:`mut-${fileSlug}-${fnSlug}-${typeSlug}-${String(patches.length+1).padStart(3,"0")}`;patches.push({id,filePath:item.filePath,functionName:item.functionName,mutationType,patch:item.patch,lineNumber:typeof item.lineNumber==="number"?item.lineNumber:void 0})}return patches}catch(error93){return log(`[generateMutants] LLM call failed: ${error93 instanceof Error?error93.message:String(error93)}; returning empty patch set`),[]}finally{await cleanup()}}init_create_tool();var generate_mutants=createSwarmTool({description:"Generate LLM-based mutation testing patches for the specified source files. Returns MutationPatch[] for direct consumption by the mutation_test tool. On LLM failure or when no patches can be generated, returns a SKIP verdict with a diagnostic message rather than throwing.",args:{files:exports_external.array(exports_external.string()).describe("Array of source file paths to generate mutation patches for")},async execute(args2,_directory,ctx){let typedArgs=args2;if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({verdict:"SKIP",patches:[],count:0,message:"generate_mutants: files must be a non-empty array"},null,2);try{let patches=await generateMutants(typedArgs.files,ctx);if(patches.length===0)return JSON.stringify({verdict:"SKIP",patches:[],count:0,message:"generate_mutants: LLM returned no patches — skipping mutation gate"},null,2);let result={verdict:"ready",patches,count:patches.length};return JSON.stringify(result,null,2)}catch(error93){let result={verdict:"SKIP",patches:[],count:0,message:`generate_mutants: unexpected error — ${error93 instanceof Error?error93.message:String(error93)}`};return JSON.stringify(result,null,2)}}});init_zod();init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_create_tool();function buildQaProfileMetadata(directory,currentPlan){let profileLookup=getProfileLookupForIdentity(directory,currentPlan);if(profileLookup.kind==="bound")return{qa_profile_hash:computeProfileHash(profileLookup.profile),qa_profile_status:"bound"};if(profileLookup.kind==="unbound_legacy")return{qa_profile_hash:null,qa_profile_status:"unbound_legacy",qa_profile_error:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",qa_profile_recovery_guidance:formatLegacyQaBindingRecovery(currentPlan,"retry get_approved_plan with the identical identity")};return{qa_profile_hash:null,qa_profile_status:"missing"}}function summarizePlan(plan){return{title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase??0,phase_count:plan.phases.length,phases:plan.phases.map((p)=>({id:p.id,name:p.name,status:p.status,task_count:p.tasks.length}))}}async function executeGetApprovedPlan(args2,directory){let currentPlan=await loadPlanJsonOnly(directory);if(!currentPlan){if(await loadLastApprovedPlan(directory))return{success:!0,approved_plan:void 0,current_plan:null,drift_detected:"unknown",current_plan_error:"plan.json not found or invalid"};return{success:!1,reason:"no_approved_snapshot"}}let expectedPlanId=derivePlanId(currentPlan),qaProfileMetadata=buildQaProfileMetadata(directory,currentPlan),approved=await loadLastApprovedPlan(directory,expectedPlanId);if(!approved){if(await loadLastApprovedPlan(directory))return{success:!0,approved_plan:void 0,current_plan:null,drift_detected:!0,current_plan_error:"Plan identity (swarm/title) was mutated after approval — "+`expected plan_id '${expectedPlanId}' but approved snapshot has a different identity. This is a form of plan tampering.`,...qaProfileMetadata};return{success:!1,reason:"no_approved_snapshot",...qaProfileMetadata}}let summaryOnly=args2.summary_only===!0,approvedPayload={plan:summaryOnly?summarizePlan(approved.plan):approved.plan,approval_metadata:approved.approval,snapshot_seq:approved.seq,snapshot_timestamp:approved.timestamp,payload_hash:approved.payloadHash,execution_profile:approved.plan.execution_profile??null},currentHash=computePlanHash(currentPlan),driftDetected=currentHash!==approved.payloadHash,currentPayload={plan:summaryOnly?summarizePlan(currentPlan):currentPlan,current_hash:currentHash};return{success:!0,approved_plan:approvedPayload,current_plan:currentPayload,drift_detected:driftDetected,...qaProfileMetadata}}var get_approved_plan=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Retrieve the last critic-approved immutable plan snapshot for baseline drift comparison. Returns the approved plan, its approval metadata, and optionally compares against the current plan.json to detect silent mutations. Read-only.",args:{summary_only:exports_external.boolean().optional().describe("When true, returns only structural metadata (title, phases, task counts) instead of full plan objects. Reduces output size for large plans.")},execute:async(args2,directory)=>{return JSON.stringify(await executeGetApprovedPlan(args2,directory),null,2)}});init_zod();init_qa_gate_profile();init_manager();init_create_tool();init_utils3();function resolveQaGatePlanIdentity(plan,args2){let hasSwarmId=args2.swarm_id!==void 0,hasPlanTitle=args2.plan_title!==void 0;if(hasSwarmId!==hasPlanTitle)return{success:!1,reason:"plan_identity_incomplete",message:"QA gate identity is incomplete: provide both swarm_id and plan_title, or neither when using the current plan."};if(!hasSwarmId&&!hasPlanTitle){if(!plan)return{success:!1,reason:"plan_identity_required",message:"Cannot resolve QA gate identity before plan.json exists. Provide both swarm_id and plan_title."};return{success:!0,planId:derivePlanId(plan),identity:plan}}let{swarm_id:swarmId,plan_title:planTitle}=args2;if(typeof swarmId!=="string"||swarmId.trim().length===0||typeof planTitle!=="string"||planTitle.trim().length===0)return{success:!1,reason:"plan_identity_invalid",message:"QA gate identity is invalid: swarm_id and plan_title must both contain non-whitespace text."};if(plan&&(plan.swarm!==swarmId||plan.title!==planTitle)&&args2.confirm_identity_change!==!0)return{success:!1,reason:"plan_identity_mismatch",message:"The explicit QA gate identity does not exactly match the current plan. Verify swarm_id and plan_title, or set confirm_identity_change: true for an intentional replacement."};return{success:!0,planId:derivePlanId({swarm:swarmId,title:planTitle}),identity:{swarm:swarmId,title:planTitle}}}async function executeGetQaGateProfile(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,lookup=getProfileLookupForIdentity(directory,identity.identity);if(lookup.kind==="missing")return{success:!1,reason:"no_profile",plan_id:planId};if(lookup.kind==="unbound_legacy")return{success:!1,reason:"plan_identity_unbound",plan_id:planId,message:`The current plan has a legacy QA gate profile row that is not exact-bound. ${formatLegacyQaBindingRecovery(identity.identity,"retry this read-only QA profile lookup")}`};let profile=lookup.profile;return{success:!0,plan_id:planId,profile:{plan_id:profile.plan_id,project_type:profile.project_type,gates:{...profile.gates},locked_at:profile.locked_at,locked_by_snapshot_seq:profile.locked_by_snapshot_seq,created_at:profile.created_at,profile_hash:computeProfileHash(profile)}}}var get_qa_gate_profile=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Retrieve the QA gate profile for the current plan. Returns the spec-level "+"gates, lock state, and a SHA-256 profile hash. Read-only — does not "+"create a profile if none exists. Uses the current plan identity by default, or an exact swarm_id + plan_title pair before plan.json exists.",args:{swarm_id:exports_external.string().refine((value)=>value.trim().length>0,"Must not be blank").optional().describe("Exact swarm identity for a pre-plan profile lookup. 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 a pre-plan profile lookup. 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.")},execute:async(args2,directory)=>{return JSON.stringify(await executeGetQaGateProfile(args2??{},directory),null,2)}});init_gh_evidence();init_zod();init_git_executable();init_path_security();init_create_tool();import*as child_process15 from"node:child_process";import*as fs160 from"node:fs";import*as path292 from"node:path";var BLAME_TIMEOUT_MS=30000,MAX_OUTPUT_LINES2=500,MAX_PATH_LENGTH2=500,MAX_LINE_NUMBER=1e6,SHELL_METACHARACTERS4=/[;|&$`(){}<>!'"]/,BINARY_EXTENSIONS=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".wmv",".flv",".zip",".tar",".gz",".rar",".7z",".bz2",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".exe",".dll",".so",".dylib",".bin",".dat",".o",".obj",".woff",".woff2",".ttf",".eot",".otf",".sqlite",".db"]);function validateFilePath(filePath){if(!filePath||filePath.length===0)return"file path is required";if(filePath.length>MAX_PATH_LENGTH2)return`file path exceeds maximum length of ${MAX_PATH_LENGTH2}`;if(path292.isAbsolute(filePath)||/^[A-Za-z]:[\\/]/.test(filePath)||filePath.startsWith("\\\\"))return"absolute paths are not allowed; use a relative path from the project root";if(containsPathTraversal(filePath))return"path traversal detected";if(containsControlChars(filePath))return"file path contains control characters";if(SHELL_METACHARACTERS4.test(filePath))return"file path contains shell metacharacters";if(filePath.startsWith("-"))return'file path cannot start with "-"';return null}function validateLineNumber(value,name){if(typeof value>"u")return null;if(typeof value!=="number"||!Number.isInteger(value)||value<1)return`${name} must be a positive integer`;if(value>MAX_LINE_NUMBER)return`${name} exceeds maximum value of ${MAX_LINE_NUMBER}`;return null}function isBinaryFile2(filePath){let ext=path292.extname(filePath).toLowerCase();return BINARY_EXTENSIONS.has(ext)}function parsePorcelainBlame(output,linesCap){let entries=[],cappedLines=output.split(`
|
|
7046
|
+
`),parsed;try{parsed=JSON.parse(extractJsonArray(rawText))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93),hint=msg.includes("EOF")||msg.includes("Unexpected end")?" (response appears truncated — LLM may have hit an output token limit)":"";return log(`[generateMutants] Failed to parse LLM response as MutationPatch[]: ${msg}${hint}; returning empty patch set`),[]}if(!Array.isArray(parsed)||parsed.length===0)return[];let patches=[];for(let item of parsed){if(typeof item!=="object"||item===null||typeof item.filePath!=="string"||typeof item.functionName!=="string"||typeof item.mutationType!=="string"||typeof item.patch!=="string")continue;let mutationType=item.mutationType,fileSlug=slugify3(item.filePath),fnSlug=slugify3(item.functionName),typeSlug=slugify3(mutationType),idStr=typeof item.id==="string"?item.id:"",id=idStr.startsWith("mut-")?idStr:`mut-${fileSlug}-${fnSlug}-${typeSlug}-${String(patches.length+1).padStart(3,"0")}`;patches.push({id,filePath:item.filePath,functionName:item.functionName,mutationType,patch:item.patch,lineNumber:typeof item.lineNumber==="number"?item.lineNumber:void 0})}return patches}catch(error93){return log(`[generateMutants] LLM call failed: ${error93 instanceof Error?error93.message:String(error93)}; returning empty patch set`),[]}finally{await cleanup()}}init_create_tool();var generate_mutants=createSwarmTool({description:"Generate LLM-based mutation testing patches for the specified source files. Returns MutationPatch[] for direct consumption by the mutation_test tool. On LLM failure or when no patches can be generated, returns a SKIP verdict with a diagnostic message rather than throwing.",args:{files:exports_external.array(exports_external.string()).describe("Array of source file paths to generate mutation patches for")},async execute(args2,_directory,ctx){let typedArgs=args2;if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({verdict:"SKIP",patches:[],count:0,message:"generate_mutants: files must be a non-empty array"},null,2);try{let patches=await generateMutants(typedArgs.files,ctx);if(patches.length===0)return JSON.stringify({verdict:"SKIP",patches:[],count:0,message:"generate_mutants: LLM returned no patches — skipping mutation gate"},null,2);let result={verdict:"ready",patches,count:patches.length};return JSON.stringify(result,null,2)}catch(error93){let result={verdict:"SKIP",patches:[],count:0,message:`generate_mutants: unexpected error — ${error93 instanceof Error?error93.message:String(error93)}`};return JSON.stringify(result,null,2)}}});init_zod();init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_create_tool();function buildQaProfileMetadata(directory,currentPlan){let profileLookup=getProfileLookupForIdentity(directory,currentPlan);if(profileLookup.kind==="bound")return{qa_profile_hash:computeProfileHash(profileLookup.profile),qa_profile_status:"bound"};if(profileLookup.kind==="unbound_legacy")return{qa_profile_hash:null,qa_profile_status:"unbound_legacy",qa_profile_error:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",qa_profile_recovery_guidance:formatLegacyQaBindingRecovery(currentPlan,"retry get_approved_plan with the identical identity")};return{qa_profile_hash:null,qa_profile_status:"missing"}}function summarizePlan(plan){return{title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase??0,phase_count:plan.phases.length,phases:plan.phases.map((p)=>({id:p.id,name:p.name,status:p.status,task_count:p.tasks.length}))}}async function executeGetApprovedPlan(args2,directory){let currentPlan=await loadPlanJsonOnly(directory);if(!currentPlan){if(await loadLastApprovedPlan(directory))return{success:!0,approved_plan:void 0,current_plan:null,drift_detected:"unknown",current_plan_error:"plan.json not found or invalid"};return{success:!1,reason:"no_approved_snapshot"}}let expectedPlanId=derivePlanId(currentPlan),qaProfileMetadata=buildQaProfileMetadata(directory,currentPlan),approved=await loadLastApprovedPlan(directory,expectedPlanId);if(!approved){if(await loadLastApprovedPlan(directory))return{success:!0,approved_plan:void 0,current_plan:null,drift_detected:!0,current_plan_error:"Plan identity (swarm/title) was mutated after approval — "+`expected plan_id '${expectedPlanId}' but approved snapshot has a different identity. This is a form of plan tampering.`,...qaProfileMetadata};return{success:!1,reason:"no_approved_snapshot",...qaProfileMetadata}}let summaryOnly=args2.summary_only===!0,approvedPayload={plan:summaryOnly?summarizePlan(approved.plan):approved.plan,approval_metadata:approved.approval,snapshot_seq:approved.seq,snapshot_timestamp:approved.timestamp,payload_hash:approved.payloadHash,execution_profile:approved.plan.execution_profile??null},currentHash=computePlanStructureHash(currentPlan),driftDetected=currentHash!==approved.payloadHash,currentPayload={plan:summaryOnly?summarizePlan(currentPlan):currentPlan,current_hash:currentHash};return{success:!0,approved_plan:approvedPayload,current_plan:currentPayload,drift_detected:driftDetected,...qaProfileMetadata}}var get_approved_plan=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Retrieve the last critic-approved immutable plan snapshot for baseline drift comparison. Returns the approved plan, its approval metadata, and optionally compares against the current plan.json to detect silent mutations. Read-only.",args:{summary_only:exports_external.boolean().optional().describe("When true, returns only structural metadata (title, phases, task counts) instead of full plan objects. Reduces output size for large plans.")},execute:async(args2,directory)=>{return JSON.stringify(await executeGetApprovedPlan(args2,directory),null,2)}});init_zod();init_qa_gate_profile();init_manager();init_create_tool();init_utils3();function resolveQaGatePlanIdentity(plan,args2){let hasSwarmId=args2.swarm_id!==void 0,hasPlanTitle=args2.plan_title!==void 0;if(hasSwarmId!==hasPlanTitle)return{success:!1,reason:"plan_identity_incomplete",message:"QA gate identity is incomplete: provide both swarm_id and plan_title, or neither when using the current plan."};if(!hasSwarmId&&!hasPlanTitle){if(!plan)return{success:!1,reason:"plan_identity_required",message:"Cannot resolve QA gate identity before plan.json exists. Provide both swarm_id and plan_title."};return{success:!0,planId:derivePlanId(plan),identity:plan}}let{swarm_id:swarmId,plan_title:planTitle}=args2;if(typeof swarmId!=="string"||swarmId.trim().length===0||typeof planTitle!=="string"||planTitle.trim().length===0)return{success:!1,reason:"plan_identity_invalid",message:"QA gate identity is invalid: swarm_id and plan_title must both contain non-whitespace text."};if(plan&&(plan.swarm!==swarmId||plan.title!==planTitle)&&args2.confirm_identity_change!==!0)return{success:!1,reason:"plan_identity_mismatch",message:"The explicit QA gate identity does not exactly match the current plan. Verify swarm_id and plan_title, or set confirm_identity_change: true for an intentional replacement."};return{success:!0,planId:derivePlanId({swarm:swarmId,title:planTitle}),identity:{swarm:swarmId,title:planTitle}}}async function executeGetQaGateProfile(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,lookup=getProfileLookupForIdentity(directory,identity.identity);if(lookup.kind==="missing")return{success:!1,reason:"no_profile",plan_id:planId};if(lookup.kind==="unbound_legacy")return{success:!1,reason:"plan_identity_unbound",plan_id:planId,message:`The current plan has a legacy QA gate profile row that is not exact-bound. ${formatLegacyQaBindingRecovery(identity.identity,"retry this read-only QA profile lookup")}`};let profile=lookup.profile;return{success:!0,plan_id:planId,profile:{plan_id:profile.plan_id,project_type:profile.project_type,gates:{...profile.gates},locked_at:profile.locked_at,locked_by_snapshot_seq:profile.locked_by_snapshot_seq,created_at:profile.created_at,profile_hash:computeProfileHash(profile)}}}var get_qa_gate_profile=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Retrieve the QA gate profile for the current plan. Returns the spec-level "+"gates, lock state, and a SHA-256 profile hash. Read-only — does not "+"create a profile if none exists. Uses the current plan identity by default, or an exact swarm_id + plan_title pair before plan.json exists.",args:{swarm_id:exports_external.string().refine((value)=>value.trim().length>0,"Must not be blank").optional().describe("Exact swarm identity for a pre-plan profile lookup. 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 a pre-plan profile lookup. 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.")},execute:async(args2,directory)=>{return JSON.stringify(await executeGetQaGateProfile(args2??{},directory),null,2)}});init_gh_evidence();init_zod();init_git_executable();init_path_security();init_create_tool();import*as child_process15 from"node:child_process";import*as fs160 from"node:fs";import*as path292 from"node:path";var BLAME_TIMEOUT_MS=30000,MAX_OUTPUT_LINES2=500,MAX_PATH_LENGTH2=500,MAX_LINE_NUMBER=1e6,SHELL_METACHARACTERS4=/[;|&$`(){}<>!'"]/,BINARY_EXTENSIONS=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".webp",".mp3",".mp4",".wav",".avi",".mov",".wmv",".flv",".zip",".tar",".gz",".rar",".7z",".bz2",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".exe",".dll",".so",".dylib",".bin",".dat",".o",".obj",".woff",".woff2",".ttf",".eot",".otf",".sqlite",".db"]);function validateFilePath(filePath){if(!filePath||filePath.length===0)return"file path is required";if(filePath.length>MAX_PATH_LENGTH2)return`file path exceeds maximum length of ${MAX_PATH_LENGTH2}`;if(path292.isAbsolute(filePath)||/^[A-Za-z]:[\\/]/.test(filePath)||filePath.startsWith("\\\\"))return"absolute paths are not allowed; use a relative path from the project root";if(containsPathTraversal(filePath))return"path traversal detected";if(containsControlChars(filePath))return"file path contains control characters";if(SHELL_METACHARACTERS4.test(filePath))return"file path contains shell metacharacters";if(filePath.startsWith("-"))return'file path cannot start with "-"';return null}function validateLineNumber(value,name){if(typeof value>"u")return null;if(typeof value!=="number"||!Number.isInteger(value)||value<1)return`${name} must be a positive integer`;if(value>MAX_LINE_NUMBER)return`${name} exceeds maximum value of ${MAX_LINE_NUMBER}`;return null}function isBinaryFile2(filePath){let ext=path292.extname(filePath).toLowerCase();return BINARY_EXTENSIONS.has(ext)}function parsePorcelainBlame(output,linesCap){let entries=[],cappedLines=output.split(`
|
|
7047
7047
|
`).slice(0,linesCap*8),commitCache=new Map,currentSha="",currentLine=0,currentAuthor="",currentAuthorTime="",currentSummary="";for(let rawLine of cappedLines){let headerMatch=rawLine.match(/^([0-9a-f]{40})\s+(\d+)\s+(\d+)/);if(headerMatch){currentSha=headerMatch[1],currentLine=Number.parseInt(headerMatch[3],10);let cached3=commitCache.get(currentSha);if(cached3)currentAuthor=cached3.author,currentAuthorTime=cached3.authorTime,currentSummary=cached3.summary;else currentAuthor="",currentAuthorTime="",currentSummary="";continue}if(rawLine.startsWith("author ")){currentAuthor=rawLine.slice(7);let meta3=commitCache.get(currentSha);if(!meta3)meta3={author:"",authorTime:"",summary:""},commitCache.set(currentSha,meta3);meta3.author=currentAuthor;continue}if(rawLine.startsWith("author-time ")){currentAuthorTime=rawLine.slice(12);let meta3=commitCache.get(currentSha);if(!meta3)meta3={author:"",authorTime:"",summary:""},commitCache.set(currentSha,meta3);meta3.authorTime=currentAuthorTime;continue}if(rawLine.startsWith("summary ")){currentSummary=rawLine.slice(8);let meta3=commitCache.get(currentSha);if(!meta3)meta3={author:"",authorTime:"",summary:""},commitCache.set(currentSha,meta3);meta3.summary=currentSummary;continue}if(rawLine.startsWith("\t")){if(entries.push({line:currentLine,sha:currentSha.slice(0,8),author:currentAuthor,authorTime:currentAuthorTime,summary:currentSummary,content:rawLine.slice(1)}),entries.length>=linesCap)break}}return entries.slice(0,linesCap)}var git_blame=createSwarmTool({description:"Analyze per-line git blame metadata for a file. Returns sha (abbreviated), author, date (ISO), summary, and content for each line. Uses git blame --porcelain. Rejects binary files and validates paths.",args:{file:exports_external.string().describe("Relative file path to blame (required, relative to project root)"),start:exports_external.number().optional().describe("Optional start line number (1-indexed). Requires end parameter."),end:exports_external.number().optional().describe("Optional end line number (1-indexed, inclusive). Requires start parameter.")},async execute(args2,directory){let fileInput,startInput,endInput;try{if(args2&&typeof args2==="object"){let obj=args2;fileInput=typeof obj.file==="string"?obj.file:void 0,startInput=typeof obj.start==="number"?obj.start:void 0,endInput=typeof obj.end==="number"?obj.end:void 0}}catch{}if(!fileInput)return JSON.stringify({error:"file path is required",file:String(fileInput??""),lineCount:0,lines:[]});let file3=fileInput,pathError=validateFilePath(file3);if(pathError)return JSON.stringify({error:pathError,file:file3,lineCount:0,lines:[]});let startError=validateLineNumber(startInput,"start");if(startError)return JSON.stringify({error:startError,file:file3,lineCount:0,lines:[]});let endError=validateLineNumber(endInput,"end");if(endError)return JSON.stringify({error:endError,file:file3,lineCount:0,lines:[]});if(startInput!==void 0&&endInput===void 0||startInput===void 0&&endInput!==void 0)return JSON.stringify({error:"both start and end must be provided together for a line range",file:file3,lineCount:0,lines:[]});if(startInput!==void 0&&endInput!==void 0&&startInput>endInput)return JSON.stringify({error:"start must be less than or equal to end",file:file3,lineCount:0,lines:[]});let resolvedPath=path292.resolve(directory,file3);if(!fs160.existsSync(resolvedPath))return JSON.stringify({error:`file not found: ${file3}`,file:file3,lineCount:0,lines:[]});let realDir=fs160.realpathSync(directory),realPath=fs160.realpathSync(resolvedPath),relative75=path292.relative(realDir,realPath);if(relative75.startsWith("..")||path292.isAbsolute(relative75))return JSON.stringify({error:"file path resolves outside the workspace",file:file3,lineCount:0,lines:[]});if(fs160.statSync(resolvedPath).isDirectory())return JSON.stringify({error:"path is a directory, not a file",file:file3,lineCount:0,lines:[]});if(isBinaryFile2(file3))return JSON.stringify({error:"binary files are not supported for git blame",file:file3,lineCount:0,lines:[]});let gitArgs=["blame","--porcelain"];if(startInput!==void 0&&endInput!==void 0)gitArgs.push("-L",`${startInput},${endInput}`);gitArgs.push("--",file3);let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return JSON.stringify({error:"git is not available or not in PATH",file:file3,lineCount:0,lines:[]})}let result=child_process15.spawnSync(gitExecutable,gitArgs,{cwd:directory,encoding:"utf-8",timeout:BLAME_TIMEOUT_MS,windowsHide:!0,maxBuffer:5242880,stdio:["ignore","pipe","pipe"]});if(result.error){if("code"in result.error&&result.error.code==="ETIMEDOUT")return JSON.stringify({error:"git blame timed out",file:file3,lineCount:0,lines:[]});let message=result.error instanceof Error?result.error.message:String(result.error);if(message.includes("ENOENT")||message.includes("not found"))return JSON.stringify({error:"git is not available or not in PATH",file:file3,lineCount:0,lines:[]});return JSON.stringify({error:`git execution failed: ${message}`,file:file3,lineCount:0,lines:[]})}if(result.status!==0){let stderr=(result.stderr??"").trim();if(stderr.includes("not a git repository")||stderr.includes("not in a git repository"))return JSON.stringify({error:"not a git repository",file:file3,lineCount:0,lines:[]});if(stderr.includes("no such path")||stderr.includes("did not match any files"))return JSON.stringify({error:`file not tracked by git: ${file3}`,file:file3,lineCount:0,lines:[]});return JSON.stringify({error:`git blame failed: ${stderr||`exit code ${result.status}`}`,file:file3,lineCount:0,lines:[]})}if(result.signal==="SIGTERM"||result.signal==="SIGKILL")return JSON.stringify({error:"git blame timed out",file:file3,lineCount:0,lines:[]});let stdout=result.stdout??"";if(!stdout.trim())return JSON.stringify({error:"no blame output (file may be empty or untracked)",file:file3,lineCount:0,lines:[]});let lines=parsePorcelainBlame(stdout,MAX_OUTPUT_LINES2).map((entry)=>({line:entry.line,sha:entry.sha,author:entry.author,date:Number.parseInt(entry.authorTime,10)>0?new Date(Number.parseInt(entry.authorTime,10)*1000).toISOString().slice(0,10):entry.authorTime,summary:entry.summary,content:entry.content})),resultJson={file:file3,lineCount:lines.length,lines};return JSON.stringify(resultJson,null,2)}});init_zod();init_knowledge_validator();function scanInvisibleFormatChars2(text){let findings=[],matches=text.match(INVISIBLE_FORMAT_CHARS);if(matches!==null&&matches.length>0)for(let match of matches)findings.push({pattern:"invisible_format_chars",field:"external_content",description:`Invisible format characters detected (${matches.length} occurrence(s))`,severity:"error",match:match.slice(0,100)});return findings}function neutralizeThreatPatterns(text,findings){if(findings.length===0)return text;let result=text;for(let finding of findings.filter((f)=>f.severity==="error")){let escapedMatch=finding.match.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pattern=new RegExp(escapedMatch,"g");result=result.replace(pattern,()=>`[EXTERNAL_CONTENT_THREAT: ${finding.pattern}] ${finding.match} [/EXTERNAL_CONTENT_THREAT]`)}return result}function scanExternalContent(text,options){let trustLevel=options?.trustLevel??"low",maxLength=options?.maxLength??50000;if(text==null)text="";let originalLength=text.length,findings=[];if(text.length>maxLength)findings.push({pattern:"oversized_content",field:"external_content",description:`External content exceeds safe size threshold (${text.length} > ${maxLength} bytes)`,severity:"error",match:`${text.length} bytes`});findings.push(...scanInvisibleFormatChars2(text));for(let entry of PROMPT_INJECTION_PATTERNS){let match=entry.pattern.exec(text);if(match!==null)findings.push({pattern:entry.name,field:"external_content",description:entry.description,severity:entry.severity,match:match[0]})}for(let entry of UNSAFE_INSTRUCTION_PATTERNS){let match=entry.pattern.exec(text);if(match!==null)findings.push({pattern:entry.name,field:"external_content",description:entry.description,severity:entry.severity,match:match[0]})}let promoteWarnings=trustLevel==="low",modulatedFindings=findings.map((f)=>promoteWarnings&&f.severity==="warning"?{...f,severity:"error"}:f),hasErrors=modulatedFindings.some((f)=>f.severity==="error"),hasWarnings=modulatedFindings.some((f)=>f.severity==="warning"),threatLevel;if(hasErrors)threatLevel="error";else if(hasWarnings)threatLevel="warning";else threatLevel="none";let neutralized=neutralizeThreatPatterns(text,modulatedFindings.filter((f)=>f.severity==="error"));return{clean:threatLevel==="none",findings:modulatedFindings,threatLevel,originalLength,neutralized}}init_create_tool();var GITINGEST_TIMEOUT_MS=1e4,GITINGEST_MAX_RESPONSE_BYTES=5242880,GITINGEST_MAX_RETRIES=2,delay3=(ms)=>new Promise((resolve130)=>setTimeout(resolve130,ms));async function fetchGitingest(args2){for(let attempt=0;attempt<=GITINGEST_MAX_RETRIES;attempt++)try{let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),GITINGEST_TIMEOUT_MS),response=await fetch("https://gitingest.com/api/ingest",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input_text:args2.url,max_file_size:args2.maxFileSize??50000,pattern:args2.pattern??"",pattern_type:args2.patternType??"exclude"}),signal:controller.signal});if(clearTimeout(timeoutId),response.status>=500&&attempt<GITINGEST_MAX_RETRIES){let backoff=200*2**attempt;await delay3(backoff);continue}if(response.status>=400&&response.status<500)throw Error(`gitingest API error: ${response.status} ${response.statusText}`);if(!response.ok)throw Error(`gitingest API error: ${response.status} ${response.statusText}`);let contentLength=Number(response.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>GITINGEST_MAX_RESPONSE_BYTES)throw Error("gitingest response too large");let text,reader=response.body?.getReader();if(reader){let buffer="",decoder=new TextDecoder,totalBytes=0;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+=value.byteLength,totalBytes>GITINGEST_MAX_RESPONSE_BYTES)throw Error("gitingest response too large");buffer+=decoder.decode(value,{stream:!0})}buffer+=decoder.decode(),text=buffer}finally{reader.cancel().catch(()=>{})}}else text=await response.text();if(Buffer.byteLength(text)>GITINGEST_MAX_RESPONSE_BYTES)throw Error("gitingest response too large");let data;try{data=JSON.parse(text)}catch{throw Error(`gitingest API returned non-JSON response (${text.length} chars, starts: ${text.slice(0,80)})`)}let combined=`${data.summary}
|
|
7048
7048
|
|
|
7049
7049
|
${data.tree}
|
|
@@ -7073,7 +7073,7 @@ Regenerated on: save_plan and phase_complete.
|
|
|
7073
7073
|
`),existing=relatedExisting.slice(0,20).map((m)=>`[${m.id}] kind=${m.kind} | ${m.text}`).join(`
|
|
7074
7074
|
`);return["You are consolidating raw episodic memory into durable semantic facts.","","Episodic events (verbatim):",episodic,"","Existing durable memories (for dedup/contradiction):",existing||"(none)","",'Emit STRICT JSON only: {"facts":[{"text":..,"kind":..,"confidence":0-1,"contradictsMemoryId"?:"mem_..."}]}',"Rules: only emit facts directly supported by the cited episodic evidence.","If uncertain, omit the fact (emit fewer facts or an empty array).",`Use durable kinds (${Array.from(DURABLE_MEMORY_KINDS).join(", ")}); keep each fact under ${CURATOR_PROMOTED_MEMORY_MAX_TEXT_LENGTH} characters.`,"Set contradictsMemoryId only when a fact directly conflicts with an existing memory above.",'Never include the literal text "## Retrieved Swarm Memory".'].join(`
|
|
7075
7075
|
`)}function aggregateEvidence(cluster,phaseNumber){let refs=new Set;for(let p of cluster)for(let ref of p.evidenceRefs)refs.add(ref);let list=Array.from(refs).slice(0,19);return list.push(`consolidation:phase-${phaseNumber}`),list}async function runConsolidationPass(input,deps){let{phaseNumber,runId,config:config3}=input,consolidation=config3.consolidation,base={skipped:!0,phaseNumber,clusterCount:0,clustersDeferred:0,decisionsEmitted:0,added:0,superseded:0,contradictionsDetected:0,deduped:0,proposed:0,memoriesDecayed:0,errored:0};if(!config3.enabled||!consolidation.enabled||!deps.gateway.isEnabled())return{...base,skipReason:"disabled"};let priorLog=await deps.readLog();if(priorLog.some((r)=>r.phaseNumber===phaseNumber))return{...base,skipReason:"already_consolidated"};let processedBefore=new Set(priorLog.flatMap((r)=>r.processedProposalIds)),startedAt=deps.now().toISOString(),logKey=runId??"unknown";await deps.logEvent({event:"consolidation_started",runId:logKey,phaseNumber,timestamp:startedAt});let pendingProposals=(await deps.gateway.listProposals({status:"pending"})).filter((p)=>p.proposedBy?.agentRole!==CONSOLIDATION_AGENT_ROLE&&!processedBefore.has(p.id)).sort((a,b)=>a.id.localeCompare(b.id)),deadAnchorMemoryIds=deps.readDeadAnchorMemoryIds?.()??new Set,existingMemories=(await deps.gateway.listMemories({})).filter((memory)=>!deadAnchorMemoryIds.has(memory.id)),clusters=clusterByJaccard(pendingProposals,(p)=>p.proposedRecord?.text??p.rationale,consolidation.jaccardThreshold),processable=clusters.slice(0,consolidation.maxClustersPerPass),clustersDeferred=Math.max(0,clusters.length-processable.length);await deps.logEvent({event:"cluster_count",runId:logKey,phaseNumber,clusterCount:clusters.length});let result={...base,skipped:!1,clusterCount:clusters.length,clustersDeferred},processedProposalIds=new Set;if(!deps.llmDelegate){if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),{...result,skipReason:"no_llm_delegate_decay_only"}}let seenFactTexts=new Set;for(let cluster of processable){if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};for(let p of cluster)processedProposalIds.add(p.id);let raw;try{let prompt=buildDistillationPrompt(cluster,existingMemories);raw=await deps.llmDelegate("",prompt,deps.signal)}catch{result.errored++;continue}let facts=parseDistillationOutput(raw),evidenceRefs=aggregateEvidence(cluster,phaseNumber);for(let fact of facts){let normalized=fact.text.replace(/\s+/g," ").trim().toLowerCase();if(seenFactTexts.has(normalized))continue;seenFactTexts.add(normalized);let plan=deriveDecision(fact,existingMemories,{autoApplyMinConfidence:consolidation.autoApplyMinConfidence,jaccardThreshold:consolidation.jaccardThreshold});try{await executePlan(plan,evidenceRefs,input,deps,result)}catch{result.errored++}}}if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),result}async function executePlan(plan,evidenceRefs,input,deps,result){let{phaseNumber}=input;if(plan.type==="skip")return;if(plan.type==="dedup"){result.deduped++;return}let newRecord={kind:plan.fact.kind,text:plan.fact.text,confidence:plan.fact.confidence,stability:"durable",source:sourceForDistilled(evidenceRefs,phaseNumber),metadata:{consolidatedFromPhase:phaseNumber}},rationale=`consolidation phase ${phaseNumber}`;if(((plan.type==="add"||plan.type==="supersede")&&EVIDENCE_REQUIRED_KINDS.has(plan.fact.kind)&&!hasRealEvidence(evidenceRefs)?"proposal":plan.type)==="proposal"){await deps.gateway.propose({operation:plan.type==="supersede"?"supersede":"add",kind:plan.fact.kind,text:plan.fact.text,rationale:plan.type==="proposal"?`${rationale}: ${plan.reason}`:`${rationale}: evidence-required kind lacks real evidence source`,evidenceRefs,...plan.type==="supersede"?{targetMemoryId:plan.oldMemoryId}:{}}),result.proposed++;return}if(plan.type==="supersede"){let proposal2=await deps.gateway.propose({operation:"supersede",kind:plan.fact.kind,text:plan.fact.text,targetMemoryId:plan.oldMemoryId,rationale,evidenceRefs});if(proposal2.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"supersede",proposalId:proposal2.id,oldMemoryId:plan.oldMemoryId,replacement:newRecord,reason:`contradiction superseded during phase ${phaseNumber} consolidation`}),result.superseded++,result.contradictionsDetected++,result.decisionsEmitted++;return}let proposal=await deps.gateway.propose({operation:"add",kind:plan.fact.kind,text:plan.fact.text,rationale,evidenceRefs});if(proposal.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"add",proposalId:proposal.id,memory:newRecord}),result.added++,result.decisionsEmitted++}async function applyDecay(memories,input,deps){let decayed=0,halfLives=input.config.consolidation.decayHalfLifeDays,now2=deps.now();for(let memory of memories){if(deps.signal?.aborted)break;if(memory.metadata.deleted===!0||memory.supersededBy)continue;if(isPastDecayHorizon(memory,halfLives,now2))continue;let nextExpiry=computeDecayExpiry(memory,halfLives,now2);if(!nextExpiry)continue;try{await deps.gateway.upsertCurated({...memory,expiresAt:nextExpiry}),decayed++}catch{}}return decayed}async function finalize2(input,deps,result,startedAt,processedProposalIds){let{phaseNumber,runId}=input,logKey=runId??"unknown",completedAt=deps.now().toISOString();await deps.logEvent({event:"decisions_emitted",runId:logKey,phaseNumber,decisionsEmitted:result.decisionsEmitted}),await deps.logEvent({event:"contradictions_detected",runId:logKey,phaseNumber,contradictionsDetected:result.contradictionsDetected}),await deps.logEvent({event:"memories_decayed",runId:logKey,phaseNumber,memoriesDecayed:result.memoriesDecayed}),await deps.logEvent({event:"consolidation_completed",runId:logKey,phaseNumber,clusterCount:result.clusterCount,decisionsEmitted:result.decisionsEmitted,contradictionsDetected:result.contradictionsDetected,memoriesDecayed:result.memoriesDecayed,timestamp:completedAt}),await deps.appendLog({phaseNumber,runId,startedAt,completedAt,clusterCount:result.clusterCount,clustersDeferred:result.clustersDeferred,decisionsEmitted:result.decisionsEmitted,added:result.added,superseded:result.superseded,contradictionsDetected:result.contradictionsDetected,deduped:result.deduped,proposed:result.proposed,memoriesDecayed:result.memoriesDecayed,errored:result.errored,processedProposalIds:Array.from(processedProposalIds)})}init_consolidation_log();init_gateway();init_reflection_service();init_run_log();init_storage_root();var CONSOLIDATION_TIMEOUT_MS=300000,runningByDirectory2=new Map;async function runMemoryConsolidation(req){let existing=runningByDirectory2.get(req.directory);if(existing)return existing;let run=(async()=>{if(!req.config.enabled||!req.config.consolidation.enabled)return{started:!1,reason:"disabled"};let gateway=createMemoryGateway({directory:req.directory,sessionID:req.sessionId,runId:req.sessionId,agentRole:"curator_consolidation"},{config:req.config}),controller=new AbortController,timer=setTimeout(()=>controller.abort(),CONSOLIDATION_TIMEOUT_MS);timer.unref?.();try{if(!gateway.isEnabled())return{started:!1,reason:"disabled"};let llmDelegate=createCuratorLLMDelegate(req.directory,"consolidation",req.sessionId),result=await runConsolidationPass({directory:req.directory,phaseNumber:req.phase,runId:req.sessionId,config:req.config},{gateway,llmDelegate,now:()=>new Date,logEvent:(event)=>appendMemoryRunLog(req.directory,req.sessionId,event),readLog:()=>readConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config)),appendLog:(record3)=>appendConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config),record3),readDeadAnchorMemoryIds:()=>readDeadAnchorMemoryIds(req.directory),signal:controller.signal});return{started:!result.skipped,reason:result.skipReason,result}}finally{clearTimeout(timer),await gateway.dispose()}})();runningByDirectory2.set(req.directory,run);try{return await run}finally{runningByDirectory2.delete(req.directory)}}function runMemoryConsolidationFireAndForget(req,onComplete,onError){queueMicrotask(()=>{runMemoryConsolidation(req).then(onComplete).catch(onError)})}init_skill_consolidation();init_snapshot_writer();init_state2();init_telemetry();init_state();init_file_locks();import*as fs167 from"node:fs";import*as path300 from"node:path";init_state4();var DEFAULT_CONFIG3={phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!1};function defaultReadPlanJson(dir){try{let planPath=path300.join(dir,".swarm","plan.json");if(!fs167.existsSync(planPath))return null;let raw=fs167.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(typeof plan!=="object"||plan===null||!Array.isArray(plan.phases))return null;return plan}catch{return null}}function readReviewerEvidenceFromFile(directory,phase){try{let evidencePath=path300.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs167.existsSync(evidencePath))return null;let raw=fs167.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED")return null;return parsed}catch{return null}}function readCriticEvidenceFromFile(directory,phase){try{let evidencePath=path300.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs167.existsSync(evidencePath))return null;let raw=fs167.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED"&&verdict!=="ESCALATE_TO_HUMAN")return null;return parsed}catch{return null}}function listLaneEvidenceSync(directory,phase){let evidenceDir=path300.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries;try{entries=fs167.readdirSync(evidenceDir)}catch{return[]}entries.sort();let laneIds=[];for(let entry of entries){if(!entry.endsWith(".json")||entry==="lean-turbo-phase.json")continue;laneIds.push(entry.slice(0,-5))}return laneIds}var _internals243={listActiveLocks,readPersisted:readPersisted3,readPlanJson:defaultReadPlanJson,readReviewerEvidence:readReviewerEvidenceFromFile,readCriticEvidence:readCriticEvidenceFromFile,listLaneEvidence,listLaneEvidenceSync,verifyLeanTurboPhaseReady};function validatePersistedShape(persisted){if(typeof persisted!=="object"||persisted===null)return!1;if(Array.isArray(persisted))return!1;if(typeof persisted.sessions!=="object")return!1;if(persisted.sessions===null)return!1;if(Array.isArray(persisted.sessions))return!1;return!0}function validateLanesArray(lanes){if(!Array.isArray(lanes))return!1;for(let lane of lanes){if(typeof lane!=="object"||lane===null)return!1;if(typeof lane.laneId!=="string")return!1;if(typeof lane.status!=="string")return!1}return!0}function validateDegradedTasksArray(degradedTasks){if(!Array.isArray(degradedTasks))return!1;for(let dt of degradedTasks){if(typeof dt!=="object"||dt===null)return!1;if(typeof dt.taskId!=="string")return!1}return!0}function verifyLeanTurboPhaseReady(directory,phase,sessionIDOrConfig,config3){let sessionID=typeof sessionIDOrConfig==="string"?sessionIDOrConfig:void 0,mergedConfig={...DEFAULT_CONFIG3,...typeof sessionIDOrConfig==="object"&&sessionIDOrConfig!==null?sessionIDOrConfig:config3??DEFAULT_CONFIG3},statePath=path300.join(directory,".swarm","turbo-state.json");if(!fs167.existsSync(statePath))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals243.readPersisted(directory);if(!persisted)return{ok:!1,reason:"Lean Turbo state unreadable or missing"};if(!validatePersistedShape(persisted))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){runState=sessionState;break}if(!runState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){runState=sessionState;break}}if(!runState)return{ok:!1,reason:sessionID?`No active Lean Turbo session for phase ${phase} and session ${sessionID}`:`No active Lean Turbo session for phase ${phase}`};if(!validateLanesArray(runState.lanes))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(!validateDegradedTasksArray(runState.degradedTasks))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(runState.lanes.length===0&&(!Array.isArray(runState.serializedTasks)||runState.serializedTasks.length===0)&&(!Array.isArray(runState.degradedTasks)||runState.degradedTasks.length===0))return{ok:!1,reason:`No lane plan or fallback tasks found for phase ${phase}`};let laneIds=runState.lanes.map((l)=>l.laneId);if(runState.lanes.length>0){for(let lane of runState.lanes)if(lane.status!=="completed"&&lane.status!=="failed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`}}if(runState.lanes.length>0){let evidenceLaneIds=new Set(_internals243.listLaneEvidenceSync(directory,phase));for(let lane of runState.lanes)if((lane.status==="completed"||lane.status==="failed")&&!evidenceLaneIds.has(lane.laneId))return{ok:!1,reason:`Lane ${lane.laneId} is ${lane.status} but lane evidence file is missing`}}let activeLocks=_internals243.listActiveLocks(directory),phaseLaneIds=new Set(laneIds);for(let lock of activeLocks)if(lock.laneId&&phaseLaneIds.has(lock.laneId))return{ok:!1,reason:`Active locks remain for lane ${lock.laneId}`};let laneTaskIds=new Set;for(let lane of runState.lanes)if(Array.isArray(lane.taskIds))for(let taskId of lane.taskIds)laneTaskIds.add(taskId);let serialDegradedTasks=runState.degradedTasks.filter((dt)=>!laneTaskIds.has(dt.taskId));if(serialDegradedTasks.length>0){let plan=_internals243.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify degraded task status: plan.json unreadable or malformed"};for(let dt of serialDegradedTasks){if(!Array.isArray(plan.phases))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phases is not an array)`};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phase ${phase} tasks is not an array)`};let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===dt.taskId);if(!task2)return{ok:!1,reason:`Degraded task ${dt.taskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Degraded task ${dt.taskId} not yet completed via standard flow`}}}let serializedTasks=runState.serializedTasks;if(Array.isArray(serializedTasks)&&serializedTasks.length>0){let plan=_internals243.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify serialized task status: plan.json unreadable or malformed"};if(!Array.isArray(plan.phases))return{ok:!1,reason:"Cannot verify serialized tasks: plan.json malformed (phases is not an array)"};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify serialized tasks: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify serialized tasks: plan.json malformed (phase ${phase} tasks is not an array)`};for(let serTaskId of serializedTasks){let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===serTaskId);if(!task2)return{ok:!1,reason:`Serialized task ${serTaskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Serialized task ${serTaskId} not yet completed (status: ${task2.status})`}}}if(mergedConfig.integrated_diff_required){let evidencePath=path300.join(directory,".swarm","evidence",String(phase),"lean-turbo-phase.json"),hasDiff=!1;try{let content=fs167.readFileSync(evidencePath,"utf-8");hasDiff=!!JSON.parse(content).integratedDiffSummary}catch{}if(!hasDiff)return{ok:!1,reason:`Integrated diff summary is required but missing for phase ${phase}`}}let reviewerVerdict=runState.lastReviewerVerdict;if(!reviewerVerdict)reviewerVerdict=_internals243.readReviewerEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_reviewer){if(reviewerVerdict!=="APPROVED")return{ok:!1,reason:"Integrated reviewer approval missing or rejected"}}let criticVerdict=runState.lastCriticVerdict;if(!criticVerdict)criticVerdict=_internals243.readCriticEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_critic){if(criticVerdict!=="APPROVED")return{ok:!1,reason:"Integrated critic approval missing or rejected"}}return{ok:!0,reason:`Phase ${phase} is ready to advance`,evidence:{lanes:laneIds,degradedTasks:runState.degradedTasks.map((dt)=>dt.taskId),reviewerVerdict:reviewerVerdict??runState.lastReviewerVerdict,criticVerdict:criticVerdict??runState.lastCriticVerdict}}}init_logger();init_create_tool();function resolveCouncilFreshnessMaxAgeMs(config3){let hours=config3?.freshnessMaxAgeHours??24;if(!Number.isFinite(hours)||hours<1)return 86400000;return Math.min(hours,720)*60*60*1000}function evaluateCouncilFreshness(input){if(input.timestampMs===null||!Number.isFinite(input.timestampMs))return{ok:!1,reason:"invalid_timestamp",message:"evidence has a missing or invalid timestamp",recovery:"Re-run the council to generate fresh, timestamped evidence."};if(input.timestampMs>input.nowMs)return{ok:!1,reason:"future_timestamp",message:"evidence timestamp is in the future",recovery:"Re-run the council after the host clock is correct, then resubmit."};if(input.nowMs-input.timestampMs>input.maxAgeMs)return{ok:!1,reason:"stale_evidence",message:`evidence is older than the configured freshness window (${Math.round(input.maxAgeMs/3600000)} hours)`,recovery:"Re-run the council for fresh review."};if(input.mustPostdateMs!==void 0&&input.mustPostdateMs!==null&&Number.isFinite(input.mustPostdateMs)){if(input.mustPostdateMs>input.nowMs)return{ok:!1,reason:"invalid_required_input",message:"a later required input (e.g. the phase retrospective) is timestamped in the future — host clock skew suspected",recovery:"Correct the host clock / fix the skewed timestamp, then re-run the council."};if(input.timestampMs<input.mustPostdateMs)return{ok:!1,reason:"predates_required_input",message:"evidence predates a later required input (e.g. the phase retrospective)",recovery:"Re-run the council after the latest required evidence is available."}}return{ok:!0,message:"evidence is fresh",recovery:""}}function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle||typeof bundle!=="object")return null;let raw=bundle,entries=Array.isArray(raw.entries)?raw.entries:[],timestamps=[parseTimestampMs(raw.created_at),parseTimestampMs(raw.updated_at),...entries.filter((entry)=>typeof entry==="object"&&entry!==null).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}init_store5();async function runArchitectureSupervisorGate(ctx){let{phase,dir,pluginConfig,agentsDispatched,safeWarn}=ctx,asConfig=pluginConfig.architectural_supervision,summarizeFindings=(findings)=>{if(!Array.isArray(findings)||findings.length===0)return"";let details=findings.map((f)=>f&&typeof f==="object"&&typeof f.description==="string"?f.description:void 0).filter((d)=>Boolean(d));return details.length>0?`
|
|
7076
|
-
Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError2){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError2)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:asEntry.timestamp?new Date(asEntry.timestamp).getTime():null,maxAgeMs:resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council)});if(!freshness.ok)return asBlocked({invalid_timestamp:"ARCH_SUPERVISOR_INVALID_TIMESTAMP",future_timestamp:"ARCH_SUPERVISOR_FUTURE_TIMESTAMP",stale_evidence:"ARCH_SUPERVISOR_STALE_EVIDENCE",predates_required_input:"ARCH_SUPERVISOR_STALE_EVIDENCE",invalid_required_input:"ARCH_SUPERVISOR_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor ${freshness.message}. ${freshness.recovery}`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase,writeEvidence:!1},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return{blocked:!0,reason:"COMPLETION_VERIFY_ERROR",message:`Phase ${phase} cannot be completed: completion verify gate encountered an error. Error: ${String(completionError)}`,agentsDispatched,agentsMissing:[],warnings:[`COMPLETION_VERIFY_ERROR: ${String(completionError)}`]}}}init_effective_spec();import*as fs168 from"node:fs";import*as path301 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanHash(plan),lookup=getProfileLookupForIdentity(dir,plan),overrides=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(lookup.kind==="missing"){let hasOverrides=Object.keys(overrides).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides}:void 0,identityBound:!0}}let profile=lookup.profile,effective=getEffectiveGates(profile,overrides);return{resolved:!0,plan,planId,planHash,effectiveGates:effective,identityBound:lookup.kind==="bound"}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved){if(preamble.identityBound===!1&&preamble.effectiveGates?.drift_check===!0)return{blocked:!0,reason:"DRIFT_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: drift_check is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path301.join(dir,".swarm","plan.json");if(fs168.existsSync(planPath)){let planRaw=fs168.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path301.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs168.readFileSync(driftEvidencePath,"utf-8"),entries=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path301.join(dir,".swarm","plan.json");if(fs168.existsSync(planPath)){let planRaw=fs168.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}import*as fs169 from"node:fs";import*as path302 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path302.normalize(path302.resolve(dir,".swarm")),retroPath=path302.normalize(path302.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path302.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path302.sep)||retroPath===baseDir))return null;try{let content=fs169.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"FINAL_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the project")}`,agentsDispatched,agentsMissing:[],warnings:[]};finalCouncilEnabled=!0;let fcPath=path302.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan:preamble.plan,config:ctx.pluginConfig.council}),completionPolicy=resolveFinalCompletionPolicy(ctx.pluginConfig.council),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council);try{let fcContent=fs169.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let fcTimeMs=parseTimestampMs(entry.timestamp),latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase),freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:fcTimeMs,maxAgeMs,mustPostdateMs:latestRetroTimestampMs});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",future_timestamp:"FINAL_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"FINAL_COUNCIL_STALE_EVIDENCE",predates_required_input:"FINAL_COUNCIL_STALE_EVIDENCE",invalid_required_input:"FINAL_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"FINAL_COUNCIL_IDENTITY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:entry.identity_version?`Phase ${phase} cannot be completed: final council evidence was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION}). Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence predates the council review identity cutover and carries no identity proof. Re-run the final council to generate identity-bound evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:entry.review_hash?"FINAL_COUNCIL_STALE_REVIEW_IDENTITY":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence does not match the current council review identity (review-relevant plan content or council policy changed since the review). Re-run the final council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"FINAL_COUNCIL_POLICY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence was produced under a different council policy. Re-run the final council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]}}let requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:COUNCIL_MEMBER_ROLES.length,rawMembersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],distinctCanonicalVoted=new Set(rawMembersVoted.map((member)=>resolveCouncilMemberRole(member)).filter((role)=>Boolean(role))),membersAbsent=COUNCIL_MEMBER_ROLES.filter((role)=>!distinctCanonicalVoted.has(role)),strictAllMembersPresent=distinctCanonicalVoted.size===COUNCIL_MEMBER_ROLES.length,quorumSatisfied=completionPolicy.mode==="quorum"?distinctCanonicalVoted.size>=requiredMembers:strictAllMembersPresent&&membersAbsent.length===0;if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<requiredMembers||!quorumSatisfied)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove the required quorum (policy ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}; recorded quorumSize: ${typeof entry.quorumSize==="number"?entry.quorumSize:"missing"}; distinct canonical members: ${distinctCanonicalVoted.size} of ${requiredMembers} required; absent: [${membersAbsent.join(", ")}]). Re-run the project-scoped final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_schema();init_manager();init_diff_source();init_evidence2();function pass(ctx,warnings=[]){return{blocked:!1,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings}}function block(ctx,reason,message,recovery={kind:"tool",action:"run_phase_review",args:{phase:ctx.phase,sessionID:ctx.sessionID}}){return{blocked:!0,reason,message,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings:[],recovery}}function evidenceStatusMatchesScope(evidenceStatus,scopeStatus){return scopeStatus==="clean"?evidenceStatus==="clean":evidenceStatus==="completed"}async function runFinalReviewGate(ctx){let config3;try{config3=resolveAutoReviewConfig(ctx.pluginConfig.auto_review??{})}catch(error93){return block(ctx,"FINAL_REVIEW_CONFIG_INVALID",`Phase ${ctx.phase} cannot be completed: ${error93 instanceof Error?error93.message:String(error93)}`,{kind:"tool",action:"swarm_command",args:{command:"doctor",args:["config"]}})}let finalPlanPhase=(await loadPlanJsonOnly(ctx.dir).catch(()=>null))?.phases.at(-1)?.id===ctx.phase,allowedTriggers=new Set;if(config3.final_review.on_phase_complete)allowedTriggers.add("phase_completion");if(finalPlanPhase&&config3.final_review.on_plan_complete)allowedTriggers.add("plan_completion");if(!config3.enabled||config3.final_review.mode!=="gate"||config3.trigger==="task_completion"||allowedTriggers.size===0)return pass(ctx);let evidence2=readAutoReviewEvidenceForPhase(ctx.dir,ctx.phase);if(!evidence2)return block(ctx,"FINAL_REVIEW_EVIDENCE_MISSING",`Phase ${ctx.phase} cannot be completed: .swarm/evidence/${ctx.phase}/auto-review.json is missing or malformed.`);if(evidence2.schema_version!==2||!evidence2.scope.manifest)return block(ctx,"FINAL_REVIEW_LEGACY_RERUN",`Phase ${ctx.phase} cannot be completed: final review evidence uses the legacy schema and must be rerun with run_phase_review before completion.`);if(evidence2.phase!==ctx.phase||!allowedTriggers.has(evidence2.trigger))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence does not match the current review scope.`);let currentScope=await _internals244.collectReviewDiff({directory:ctx.dir,maxBytes:config3.final_review.max_diff_bytes});if(currentScope.status==="error")return block(ctx,"FINAL_REVIEW_SCOPE_COLLECTION_FAILED",`Phase ${ctx.phase} cannot be completed: terminal final-review scope collection failed (${currentScope.reason}).`);let currentManifest=await materializeAutoReviewManifest(ctx.dir,currentScope.manifest,config3);if(currentManifest.hash!==evidence2.scope.manifest.hash||JSON.stringify(currentScope.selector)!==JSON.stringify(evidence2.scope.selector)||JSON.stringify(currentScope.completeness)!==JSON.stringify(evidence2.scope.completeness)||!evidenceStatusMatchesScope(evidence2.review.status,currentScope.status))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: repository scope, plan requirements, or review policy changed after final review evidence was produced.`);if(evidence2.policy.mode!==config3.final_review.mode||evidence2.policy.min_confidence!==config3.min_confidence||evidence2.policy.structured_findings!==config3.structured_findings||evidence2.policy.validate_findings!==config3.validate_findings||evidence2.policy.digest!==currentManifest.review_policy_digest)return block(ctx,"FINAL_REVIEW_POLICY_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence was produced under a different policy.`);let integrity=validateAutoReviewEvidenceIntegrity(ctx.dir,evidence2,{scopeHash:evidence2.scope.hash,phase:ctx.phase,trigger:evidence2.trigger,policy:{mode:evidence2.policy.mode,min_confidence:evidence2.policy.min_confidence,structured_findings:evidence2.policy.structured_findings,validate_findings:evidence2.policy.validate_findings},scopeContent:currentScope.canonicalText});if(!integrity.ok)return block(ctx,integrity.code==="receipt_missing"?"FINAL_REVIEW_RECEIPT_MISSING":"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: final review evidence integrity check failed (${integrity.reason}).`);if(evidence2.review.status==="error")return block(ctx,"FINAL_REVIEW_FAILED",`Phase ${ctx.phase} cannot be completed: final review dispatch or parsing failed.`);if(!evidence2.scope.completeness.complete)return block(ctx,"FINAL_REVIEW_SCOPE_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: final review scope was truncated or incomplete.`);if(evidence2.review.status==="completed"&&evidence2.review.output_mode!=="structured")return block(ctx,"FINAL_REVIEW_STRUCTURED_EVIDENCE_REQUIRED",`Phase ${ctx.phase} cannot be completed: gate mode requires structured review evidence.`);if(!evidence2.validation_complete)return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: independent finding validation evidence is incomplete.`);let gateCandidates=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical"));if(gateCandidates.some((finding)=>!finding.validation||finding.validation.finding_id!==finding.finding_id))return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: gate-eligible findings lack exact-ID validation evidence.`);let confirmedIds=gateCandidates.filter((finding)=>finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(confirmedIds.length!==recordedBlockingIds.length||confirmedIds.some((id,index)=>id!==recordedBlockingIds[index]))return block(ctx,"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: blocking finding IDs do not match independently confirmed findings.`);if(evidence2.blocking_finding_ids.length>0)return block(ctx,"FINAL_REVIEW_CONFIRMED_FINDINGS",`Phase ${ctx.phase} cannot be completed: ${evidence2.blocking_finding_ids.length} anchored HIGH/CRITICAL finding(s) were independently CONFIRMED.`);return pass(ctx)}var _internals244={collectReviewDiff};import*as fs170 from"node:fs";import*as path303 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,hallucinationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){if(hallucinationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let hgPath=path303.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs170.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){if(hallucinationGateEnabled)return{blocked:!0,reason:"HALLUCINATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: hallucination guard gate encountered an error when hallucination_guard was enabled. Error: ${String(hgError)}`,agentsDispatched,agentsMissing:[],warnings:[`HALLUCINATION_GATE_ERROR: ${String(hgError)}`]};else safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs171 from"node:fs";import*as path304 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,mutationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){if(mutationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"MUTATION_GATE_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: mutation_test is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let mgPath=path304.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs171.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){if(mutationGateEnabled)return{blocked:!0,reason:"MUTATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: mutation gate encountered an error when mutation_test was enabled. Error: ${String(mgError)}`,agentsDispatched,agentsMissing:[],warnings:[`MUTATION_GATE_ERROR: ${String(mgError)}`]};else safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs172 from"node:fs";import*as path305 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path305.normalize(path305.resolve(dir,".swarm")),retroPath=path305.normalize(path305.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path305.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path305.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs172.readFileSync(retroPath,"utf-8")),phase)}catch{return null}}async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"PHASE_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: phase_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};councilModeEnabled=!0;let identity=computeCouncilReviewIdentity({level:"phase",scope:{kind:"phase",phaseNumber:phase},plan:preamble.plan??null,config:pluginConfig.council}),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(pluginConfig.council),pcPath=path305.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs172.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){if(pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0,pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]};let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:parseTimestampMs(entry.timestamp),maxAgeMs,mustPostdateMs:latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs2(dir,phase)});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"PHASE_COUNCIL_INVALID_TIMESTAMP",future_timestamp:"PHASE_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"PHASE_COUNCIL_STALE_EVIDENCE",predates_required_input:"PHASE_COUNCIL_STALE_EVIDENCE",invalid_required_input:"PHASE_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"PHASE_COUNCIL_IDENTITY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence ${entry.identity_version?`was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION})`:"predates the council review identity cutover and carries no identity proof"}. Re-convene the phase council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_REVIEW_IDENTITY",message:`Phase ${phase} cannot be completed: phase council evidence does not match the current council review identity (review-relevant plan content changed since the review). Re-convene the phase council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"PHASE_COUNCIL_POLICY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence was produced under a different council policy. Re-convene the phase council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
|
|
7076
|
+
Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError2){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError2)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:asEntry.timestamp?new Date(asEntry.timestamp).getTime():null,maxAgeMs:resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council)});if(!freshness.ok)return asBlocked({invalid_timestamp:"ARCH_SUPERVISOR_INVALID_TIMESTAMP",future_timestamp:"ARCH_SUPERVISOR_FUTURE_TIMESTAMP",stale_evidence:"ARCH_SUPERVISOR_STALE_EVIDENCE",predates_required_input:"ARCH_SUPERVISOR_STALE_EVIDENCE",invalid_required_input:"ARCH_SUPERVISOR_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor ${freshness.message}. ${freshness.recovery}`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase,writeEvidence:!1},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return{blocked:!0,reason:"COMPLETION_VERIFY_ERROR",message:`Phase ${phase} cannot be completed: completion verify gate encountered an error. Error: ${String(completionError)}`,agentsDispatched,agentsMissing:[],warnings:[`COMPLETION_VERIFY_ERROR: ${String(completionError)}`]}}}init_effective_spec();import*as fs168 from"node:fs";import*as path301 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanLedgerHash(plan),lookup=getProfileLookupForIdentity(dir,plan),overrides=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(lookup.kind==="missing"){let hasOverrides=Object.keys(overrides).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides}:void 0,identityBound:!0}}let profile=lookup.profile,effective=getEffectiveGates(profile,overrides);return{resolved:!0,plan,planId,planHash,effectiveGates:effective,identityBound:lookup.kind==="bound"}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved){if(preamble.identityBound===!1&&preamble.effectiveGates?.drift_check===!0)return{blocked:!0,reason:"DRIFT_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: drift_check is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path301.join(dir,".swarm","plan.json");if(fs168.existsSync(planPath)){let planRaw=fs168.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path301.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs168.readFileSync(driftEvidencePath,"utf-8"),entries=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path301.join(dir,".swarm","plan.json");if(fs168.existsSync(planPath)){let planRaw=fs168.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}import*as fs169 from"node:fs";import*as path302 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path302.normalize(path302.resolve(dir,".swarm")),retroPath=path302.normalize(path302.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path302.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path302.sep)||retroPath===baseDir))return null;try{let content=fs169.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"FINAL_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the project")}`,agentsDispatched,agentsMissing:[],warnings:[]};finalCouncilEnabled=!0;let fcPath=path302.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan:preamble.plan,config:ctx.pluginConfig.council}),completionPolicy=resolveFinalCompletionPolicy(ctx.pluginConfig.council),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council);try{let fcContent=fs169.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let fcTimeMs=parseTimestampMs(entry.timestamp),latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase),freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:fcTimeMs,maxAgeMs,mustPostdateMs:latestRetroTimestampMs});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",future_timestamp:"FINAL_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"FINAL_COUNCIL_STALE_EVIDENCE",predates_required_input:"FINAL_COUNCIL_STALE_EVIDENCE",invalid_required_input:"FINAL_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"FINAL_COUNCIL_IDENTITY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:entry.identity_version?`Phase ${phase} cannot be completed: final council evidence was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION}). Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence predates the council review identity cutover and carries no identity proof. Re-run the final council to generate identity-bound evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:entry.review_hash?"FINAL_COUNCIL_STALE_REVIEW_IDENTITY":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence does not match the current council review identity (review-relevant plan content or council policy changed since the review). Re-run the final council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"FINAL_COUNCIL_POLICY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence was produced under a different council policy. Re-run the final council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]}}let requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:COUNCIL_MEMBER_ROLES.length,rawMembersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],distinctCanonicalVoted=new Set(rawMembersVoted.map((member)=>resolveCouncilMemberRole(member)).filter((role)=>Boolean(role))),membersAbsent=COUNCIL_MEMBER_ROLES.filter((role)=>!distinctCanonicalVoted.has(role)),strictAllMembersPresent=distinctCanonicalVoted.size===COUNCIL_MEMBER_ROLES.length,quorumSatisfied=completionPolicy.mode==="quorum"?distinctCanonicalVoted.size>=requiredMembers:strictAllMembersPresent&&membersAbsent.length===0;if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<requiredMembers||!quorumSatisfied)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove the required quorum (policy ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}; recorded quorumSize: ${typeof entry.quorumSize==="number"?entry.quorumSize:"missing"}; distinct canonical members: ${distinctCanonicalVoted.size} of ${requiredMembers} required; absent: [${membersAbsent.join(", ")}]). Re-run the project-scoped final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_schema();init_manager();init_diff_source();init_evidence2();function pass(ctx,warnings=[]){return{blocked:!1,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings}}function block(ctx,reason,message,recovery={kind:"tool",action:"run_phase_review",args:{phase:ctx.phase,sessionID:ctx.sessionID}}){return{blocked:!0,reason,message,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings:[],recovery}}function evidenceStatusMatchesScope(evidenceStatus,scopeStatus){return scopeStatus==="clean"?evidenceStatus==="clean":evidenceStatus==="completed"}async function runFinalReviewGate(ctx){let config3;try{config3=resolveAutoReviewConfig(ctx.pluginConfig.auto_review??{})}catch(error93){return block(ctx,"FINAL_REVIEW_CONFIG_INVALID",`Phase ${ctx.phase} cannot be completed: ${error93 instanceof Error?error93.message:String(error93)}`,{kind:"tool",action:"swarm_command",args:{command:"doctor",args:["config"]}})}let finalPlanPhase=(await loadPlanJsonOnly(ctx.dir).catch(()=>null))?.phases.at(-1)?.id===ctx.phase,allowedTriggers=new Set;if(config3.final_review.on_phase_complete)allowedTriggers.add("phase_completion");if(finalPlanPhase&&config3.final_review.on_plan_complete)allowedTriggers.add("plan_completion");if(!config3.enabled||config3.final_review.mode!=="gate"||config3.trigger==="task_completion"||allowedTriggers.size===0)return pass(ctx);let evidence2=readAutoReviewEvidenceForPhase(ctx.dir,ctx.phase);if(!evidence2)return block(ctx,"FINAL_REVIEW_EVIDENCE_MISSING",`Phase ${ctx.phase} cannot be completed: .swarm/evidence/${ctx.phase}/auto-review.json is missing or malformed.`);if(evidence2.schema_version!==2||!evidence2.scope.manifest)return block(ctx,"FINAL_REVIEW_LEGACY_RERUN",`Phase ${ctx.phase} cannot be completed: final review evidence uses the legacy schema and must be rerun with run_phase_review before completion.`);if(evidence2.phase!==ctx.phase||!allowedTriggers.has(evidence2.trigger))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence does not match the current review scope.`);let currentScope=await _internals244.collectReviewDiff({directory:ctx.dir,maxBytes:config3.final_review.max_diff_bytes});if(currentScope.status==="error")return block(ctx,"FINAL_REVIEW_SCOPE_COLLECTION_FAILED",`Phase ${ctx.phase} cannot be completed: terminal final-review scope collection failed (${currentScope.reason}).`);let currentManifest=await materializeAutoReviewManifest(ctx.dir,currentScope.manifest,config3);if(currentManifest.hash!==evidence2.scope.manifest.hash||JSON.stringify(currentScope.selector)!==JSON.stringify(evidence2.scope.selector)||JSON.stringify(currentScope.completeness)!==JSON.stringify(evidence2.scope.completeness)||!evidenceStatusMatchesScope(evidence2.review.status,currentScope.status))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: repository scope, plan requirements, or review policy changed after final review evidence was produced.`);if(evidence2.policy.mode!==config3.final_review.mode||evidence2.policy.min_confidence!==config3.min_confidence||evidence2.policy.structured_findings!==config3.structured_findings||evidence2.policy.validate_findings!==config3.validate_findings||evidence2.policy.digest!==currentManifest.review_policy_digest)return block(ctx,"FINAL_REVIEW_POLICY_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence was produced under a different policy.`);let integrity=validateAutoReviewEvidenceIntegrity(ctx.dir,evidence2,{scopeHash:evidence2.scope.hash,phase:ctx.phase,trigger:evidence2.trigger,policy:{mode:evidence2.policy.mode,min_confidence:evidence2.policy.min_confidence,structured_findings:evidence2.policy.structured_findings,validate_findings:evidence2.policy.validate_findings},scopeContent:currentScope.canonicalText});if(!integrity.ok)return block(ctx,integrity.code==="receipt_missing"?"FINAL_REVIEW_RECEIPT_MISSING":"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: final review evidence integrity check failed (${integrity.reason}).`);if(evidence2.review.status==="error")return block(ctx,"FINAL_REVIEW_FAILED",`Phase ${ctx.phase} cannot be completed: final review dispatch or parsing failed.`);if(!evidence2.scope.completeness.complete)return block(ctx,"FINAL_REVIEW_SCOPE_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: final review scope was truncated or incomplete.`);if(evidence2.review.status==="completed"&&evidence2.review.output_mode!=="structured")return block(ctx,"FINAL_REVIEW_STRUCTURED_EVIDENCE_REQUIRED",`Phase ${ctx.phase} cannot be completed: gate mode requires structured review evidence.`);if(!evidence2.validation_complete)return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: independent finding validation evidence is incomplete.`);let gateCandidates=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical"));if(gateCandidates.some((finding)=>!finding.validation||finding.validation.finding_id!==finding.finding_id))return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: gate-eligible findings lack exact-ID validation evidence.`);let confirmedIds=gateCandidates.filter((finding)=>finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(confirmedIds.length!==recordedBlockingIds.length||confirmedIds.some((id,index)=>id!==recordedBlockingIds[index]))return block(ctx,"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: blocking finding IDs do not match independently confirmed findings.`);if(evidence2.blocking_finding_ids.length>0)return block(ctx,"FINAL_REVIEW_CONFIRMED_FINDINGS",`Phase ${ctx.phase} cannot be completed: ${evidence2.blocking_finding_ids.length} anchored HIGH/CRITICAL finding(s) were independently CONFIRMED.`);return pass(ctx)}var _internals244={collectReviewDiff};import*as fs170 from"node:fs";import*as path303 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,hallucinationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){if(hallucinationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let hgPath=path303.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs170.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){if(hallucinationGateEnabled)return{blocked:!0,reason:"HALLUCINATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: hallucination guard gate encountered an error when hallucination_guard was enabled. Error: ${String(hgError)}`,agentsDispatched,agentsMissing:[],warnings:[`HALLUCINATION_GATE_ERROR: ${String(hgError)}`]};else safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs171 from"node:fs";import*as path304 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,mutationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){if(mutationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"MUTATION_GATE_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: mutation_test is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let mgPath=path304.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs171.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){if(mutationGateEnabled)return{blocked:!0,reason:"MUTATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: mutation gate encountered an error when mutation_test was enabled. Error: ${String(mgError)}`,agentsDispatched,agentsMissing:[],warnings:[`MUTATION_GATE_ERROR: ${String(mgError)}`]};else safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs172 from"node:fs";import*as path305 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path305.normalize(path305.resolve(dir,".swarm")),retroPath=path305.normalize(path305.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path305.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path305.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs172.readFileSync(retroPath,"utf-8")),phase)}catch{return null}}async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"PHASE_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: phase_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};councilModeEnabled=!0;let identity=computeCouncilReviewIdentity({level:"phase",scope:{kind:"phase",phaseNumber:phase},plan:preamble.plan??null,config:pluginConfig.council}),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(pluginConfig.council),pcPath=path305.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs172.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){if(pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0,pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]};let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:parseTimestampMs(entry.timestamp),maxAgeMs,mustPostdateMs:latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs2(dir,phase)});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"PHASE_COUNCIL_INVALID_TIMESTAMP",future_timestamp:"PHASE_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"PHASE_COUNCIL_STALE_EVIDENCE",predates_required_input:"PHASE_COUNCIL_STALE_EVIDENCE",invalid_required_input:"PHASE_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"PHASE_COUNCIL_IDENTITY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence ${entry.identity_version?`was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION})`:"predates the council review identity cutover and carries no identity proof"}. Re-convene the phase council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_REVIEW_IDENTITY",message:`Phase ${phase} cannot be completed: phase council evidence does not match the current council review identity (review-relevant plan content changed since the review). Re-convene the phase council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"PHASE_COUNCIL_POLICY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence was produced under a different council policy. Re-convene the phase council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
|
|
7077
7077
|
Required fixes: ${requiredFixes.map((f)=>f.detail??JSON.stringify(f)).join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_REJECTED",message:`Phase ${phase} cannot be completed: phase council returned verdict 'REJECT'. Address the required fixes before completing the phase.${fixesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}if(entry.verdict==="CONCERNS"||entry.verdict==="concerns"){if(!(pluginConfig.council?.phaseConcernsAllowComplete??!0)){let advisoryNotes=entry.advisoryNotes??entry.advisory_notes??[],notesDetail=Array.isArray(advisoryNotes)&&advisoryNotes.length>0?`
|
|
7078
7078
|
Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import{createHash as createHash81}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action)return{kind:"tool",action};if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries){return createHash81("sha256").update(JSON.stringify({schemaVersion:1,phase,entries})).digest("hex")}async function collectPhaseGateReport(input){let entries=[];for(let check3 of input.checks){if(check3.applicable===!1){entries.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries),entries}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash82}from"node:crypto";import*as fs173 from"node:fs";import*as path306 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative78=path306.relative(root,candidate2);return relative78===""||relative78!==".."&&!relative78.startsWith(`..${path306.sep}`)&&!path306.isAbsolute(relative78)}function computePhaseEvidenceSnapshot(directory){let root=fs173.realpathSync(directory),entries=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat23;try{stat23=fs173.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat23.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path306.relative(root,absolute)}`);if(stat23.isDirectory()){let names=[],handle=fs173.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path306.join(absolute,name));return}if(!stat23.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path306.relative(root,absolute)}`);if(entries.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat23.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs173.openSync(absolute,fs173.constants.O_RDONLY|(fs173.constants.O_NOFOLLOW??0));try{let opened=fs173.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat23.dev||opened.ino!==stat23.ino||opened.size!==stat23.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs173.readFileSync(descriptor),after=fs173.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries.push({path:path306.relative(root,absolute).replaceAll("\\","/"),sha256:createHash82("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs173.closeSync(descriptor)}};for(let relative78 of INPUTS)visit(path306.join(root,...relative78.split("/")));return entries.sort((left,right)=>compareUtf8(left.path,right.path)),createHash82("sha256").update(JSON.stringify({schemaVersion:1,entries})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel});if(!directiveGate.blocked)return passGate();return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals243.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let planRaw=fs175.readFileSync(validateSwarmPath(dir,"plan.json"),"utf8"),target=JSON.parse(planRaw).phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash83("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs175.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash83("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path308.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs175.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs175.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs175.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs175.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries=taskEvidenceResult.bundle.entries??[];for(let entry of entries)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),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."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_create_tool();import*as fs176 from"node:fs";import*as path309 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000,_internals246={bunSpawn};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs176.existsSync(path309.join(cwd,"package.json")))ecosystems.push("npm");if(fs176.existsSync(path309.join(cwd,"pyproject.toml"))||fs176.existsSync(path309.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs176.existsSync(path309.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs176.existsSync(path309.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs176.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs176.existsSync(path309.join(cwd,"Gemfile"))||fs176.existsSync(path309.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs176.existsSync(path309.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs176.existsSync(path309.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=["npm","audit","--json"];try{let proc=_internals246.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity){switch(severity.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=["cargo","audit","--json"];try{let proc=_internals246.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
|
|
7079
7079
|
`).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.vulnerabilities?.list)for(let item of obj.vulnerabilities.list){let cvss=item.advisory.cvss||0,severity=mapCargoSeverity(cvss);findings.push({package:item.advisory.package,installedVersion:item.package.version,patchedVersion:item.versions.patched&&item.versions.patched.length>0?item.versions.patched[0]:null,severity,title:item.advisory.title,cve:item.advisory.aliases&&item.advisory.aliases.length>0?item.advisory.aliases[0]:item.advisory.id?item.advisory.id:null,url:item.advisory.url||null})}}catch{}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"cargo",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return cargoAuditFailure(command,error93)}}function mapCargoSeverity(cvss){if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runGoAudit(directory){let command=["govulncheck","-json","./..."];if(!isCommandAvailable("govulncheck"))return warn("[pkg-audit] govulncheck not found, skipping Go audit"),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"govulncheck not installed. Install with: go install golang.org/x/vuln/cmd/govulncheck@latest"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve137)=>setTimeout(()=>resolve137("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==3)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck exited with code ${exitCode}`};if(exitCode===0)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let osvMap=new Map,goFindings=[],lines=stdout.split(`
|
|
@@ -7119,7 +7119,7 @@ ${paginatedContent}`;if(endLine<totalLines){let remaining=totalLines-endLine;res
|
|
|
7119
7119
|
${result.stderr}`;return/(?:\b(?:ran|running|collected)\s+0\s+(?:tests?|items?)\b|\btests? run:\s*0\b|\b0\s+(?:tests?\s+(?:ran|passed)|pass(?:ed)?|passing|examples?)\b|\bno tests? (?:ran|to run|found|were found|executed|is available)\b|\bno test is available\b|\btests? (?:are|were) skipped\b|\btest\b[^\n]*\bskipped\b|\bNO-SOURCE\b|\[no test files\])/i.test(output)}function reproductionSelectorValues(command){let runnerVerbs=new Set(["run","run-script","test","tests","spec","check"]),selectorFlags=new Set(["--test-name-pattern","--testNamePattern","--tests","--filter","--grep","-k","-m","-run"]),selectors=new Set;for(let index=1;index<command.length;index+=1){let arg=command[index];if(selectorFlags.has(arg)){let value=command[index+1];if(value&&!value.startsWith("-"))selectors.add(value);index+=1;continue}let assignment=arg.match(/^(?:--(?:test-name-pattern|testNamePattern|tests|filter|grep)|-run|-Dtest)=(.+)$/);if(assignment?.[1]){selectors.add(assignment[1]);continue}if(arg.startsWith("-")||arg.startsWith("/"))continue;if(runnerVerbs.has(arg.toLowerCase()))continue;selectors.add(arg)}return selectors}function isPlausibleTypecheckCommand(executable,args2,_directCommandName){if(executable==="go")return args2[0]==="vet"&&!args2.some((arg)=>/^-n(?:=.*)?$/i.test(arg));if(executable==="flow")return["check","status","focus-check"].includes(args2[0]?.toLowerCase());if(executable==="phpstan")return["analyse","analyze"].includes(args2[0]?.toLowerCase())&&!args2.some((arg)=>/^--generate-baseline(?:=.*)?$/i.test(arg));return/^(?:tsc|pyright|mypy|sorbet|psalm)$/.test(executable)||executable==="cargo"&&args2[0]==="check"||executable==="dotnet"&&args2[0]==="build"}function isPlausibleReproductionCommand(executable,args2,_directCommandName,_commandPath){if(executable==="python"||executable==="python3")return args2[0]==="-m"&&args2[1]?.toLowerCase()==="pytest";if(executable==="bundle")return args2[0]==="exec"&&args2[1]?.toLowerCase()==="rspec";if(executable==="cargo")return args2[0]==="test"||args2[0]==="nextest"&&args2[1]?.toLowerCase()==="run";if(executable==="go")return args2[0]==="test"&&!args2.some((arg)=>/^(?:-c|-list(?:=.*)?)$/i.test(arg));if(executable==="node")return args2[0]==="--test";if(executable==="deno")return args2[0]==="test";if(executable==="zig")return args2[0]==="test";if(executable==="meson")return args2[0]==="test";if(executable==="make"||executable==="ninja")return args2.some((arg)=>/^(?:test|check|verify|regression)$/i.test(arg));if(executable==="playwright")return args2[0]==="test";if(executable==="dart"||executable==="flutter")return args2[0]==="test";if(executable==="xcodebuild")return args2.some((arg)=>["test","test-without-building"].includes(arg.toLowerCase()))&&!args2.some((arg)=>/^-(?:list|enumerate-tests|showBuildSettings|showdestinations|showTestPlans|showsdks|version|help)$/i.test(arg));if(executable==="cypress")return args2[0]==="run";if(/^(?:pytest|ctest|rspec|phpunit|vitest|jest|mocha|ava|go-test-sum)$/.test(executable))return!0;if(executable==="dotnet")return args2[0]?.toLowerCase()==="test";if(["mvn","mvnw"].includes(executable))return args2.some((arg)=>/^(?:test|verify|integration-test|failsafe:integration-test)$/i.test(arg));if(["gradle","gradlew"].includes(executable)){let invokesExecutableTestTask=args2.some((arg)=>{if(arg.startsWith("-"))return!1;let task2=arg.split(":").filter(Boolean).at(-1)??"";if(/^(?:compile|process|generate|assemble|classes|jar|source|kapt|prepare)/i.test(task2))return!1;return task2.toLowerCase()==="test"||/^test[A-Z0-9_-]/.test(task2)&&/Test$/.test(task2)||/^[a-z][A-Za-z0-9_-]*Test$/.test(task2)});return!args2.some((arg)=>/^(?:-m|--dry-run)(?:=.*)?$/i.test(arg))&&invokesExecutableTestTask}return!1}function isPlausibleStageACommand(category,command){if(category==="diff-check")return isExactDiffCheck(command);let executable=path321.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");if(BLOCKED_EXECUTABLES.has(executable))return!1;if(command.slice(1).some((arg)=>/^(?:-h|--help|--version|version|help|list|-N|--fixtures(?:-per-test)?|--markers|--trace-config|--cache-show|--list(?:-?(?:tests?|suites|groups))?(?:-xml)?(?:=.*)?|--show-only(?:=.*)?|--print-labels|--listFilesOnly|--noCheck|--no-check|--no-run(?:=.*)?|--test-dry-run(?:=.*)?|--createStub|--createstub|--print-config|--env-info|--show-settings|--show-files|--list-msgs|--generate-rcfile|--show-?config(?:=.*)?|--init|--dry-run(?:=.*)?|--collect-only|--setup-(?:only|plan)|--co|--if-present(?:=.*)?)$/i.test(arg)))return!1;if(command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))||["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))return!1;if(category==="lint"&&command.some((arg)=>/^(?:--fix(?:-only)?|--write|--apply|--auto-?correct)(?:=.*)?$|^-[aAw]$/.test(arg)))return!1;if(category==="reproduction"&&(command.some((arg)=>/^(?:--passWithNoTests|--allow-no-tests|--collect-only|--list|--dry-run|--only|--todo|--update-snapshot|--bless|--accept|-w|-x(?:.+)?|--exclude-task(?:=.+)?)$/i.test(arg))||command.some((arg)=>/^-D(?:skipTests|skipITs|maven\.test\.(?:skip|skip\.exec))(?:=true)?$/i.test(arg))))return!1;if(["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&["build","run","test"].includes(command[1]))return isPlausiblePackageManagerCommand(category,executable,command.slice(1));if(executable==="npx")return isPlausiblePackageManagerCommand(category,executable,command.slice(1));let directCommandName=executable.replace(/\.(?:sh|ps1|py|js|mjs|cjs|rb|pl)$/,"");switch(category){case"build":return isPlausibleBuildCommand(executable,command.slice(1));case"typecheck":return isPlausibleTypecheckCommand(executable,command.slice(1),directCommandName);case"lint":return isPlausibleLintCommand(executable,command.slice(1),directCommandName);case"reproduction":return isPlausibleReproductionCommand(executable,command.slice(1),directCommandName,command[0])}}function readBoundedText(filePath){try{let stat23=fs185.statSync(filePath);if(!stat23.isFile()||stat23.size>524288)return;return fs185.readFileSync(filePath,"utf8")}catch{return}}function readPresentRepositoryText(directory,filePath,label){let stat23;try{stat23=fs185.statSync(filePath)}catch(error93){if(error93.code==="ENOENT")return;throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}if(!stat23.isFile()||stat23.size>524288)throw Error(`BLOCKED: Stage A cannot inspect present ${label}`);try{let canonicalRoot=fs185.realpathSync(path321.resolve(directory)),canonicalFile=fs185.realpathSync(filePath),relative84=path321.relative(canonicalRoot,canonicalFile);if(relative84===".."||relative84.startsWith(`..${path321.sep}`)||path321.isAbsolute(relative84))throw Error("escaping manifest");return fs185.readFileSync(canonicalFile,"utf8")}catch{throw Error(`BLOCKED: Stage A cannot inspect present ${label}`)}}function resolveContainedDirectory(directory,workingDirectory="."){let root=path321.resolve(directory),canonicalRoot=(()=>{try{return fs185.realpathSync(root)}catch{return root}})(),candidate2=path321.resolve(root,workingDirectory);try{if(!fs185.statSync(candidate2).isDirectory())return;let absolute=fs185.realpathSync(candidate2),relativePath2=path321.relative(canonicalRoot,absolute);if(relativePath2===".."||relativePath2.startsWith(`..${path321.sep}`)||path321.isAbsolute(relativePath2))return;return{absolute,relative:relativePath2.replaceAll("\\","/")||"."}}catch{return}}function readRepositoryValidationContract(directory,contractPath){let root=path321.resolve(directory),canonicalRoot=(()=>{try{return fs185.realpathSync(root)}catch{return root}})(),resolved=path321.resolve(root,contractPath),canonicalContract;try{canonicalContract=fs185.realpathSync(resolved)}catch{return}let relative84=path321.relative(canonicalRoot,canonicalContract);if(!relative84||relative84===".."||relative84.startsWith(`..${path321.sep}`)||path321.isAbsolute(relative84)||path321.basename(canonicalContract)!==".pr-validation.json")return;let text=readBoundedText(canonicalContract);if(!text)return;try{return RepositoryValidationContractSchema.parse(JSON.parse(text))}catch{return}}async function resolveContractBaseProvenance(directory,prHeadSha,baseRef,baseSha){if(!baseRef&&!baseSha)return;if(!baseRef||!baseSha)throw Error("BLOCKED: Stage A contract authorization requires both base_ref and base_sha");let resolvedBase=await _internals253.resolveExactMergeBaseAsync(directory,baseRef,prHeadSha);if(!resolvedBase||resolvedBase.toLowerCase()!==baseSha.toLowerCase()||resolvedBase.toLowerCase()===prHeadSha.toLowerCase())throw Error("Stage A contract authorization requires base_sha to be the immutable merge base of base_ref and pr_head_sha");return{baseRef,baseSha:resolvedBase.toLowerCase()}}function readTrustedRepositoryValidationContract(directory,contractPath,provenance){if(!provenance)return;let current=readRepositoryValidationContract(directory,contractPath),currentText=readBoundedText(path321.resolve(directory,contractPath)),baseText=_internals253.readGitTextAtRevision(directory,provenance.baseSha,contractPath.replaceAll("\\","/").replace(/^\.\//,""));if(!current||!currentText||baseText===null||currentText!==baseText)return;return current}function isExactRepositoryContractValidator(directory,check3,provenance){if(!check3.validator_contract)return!1;let validator=readTrustedRepositoryValidationContract(directory,check3.validator_contract.path,provenance)?.validators.find((candidate2)=>candidate2.id===check3.validator_contract?.id);if(!validator||validator.category!==check3.category)return!1;let requestedDirectory=resolveContainedDirectory(directory,check3.working_directory??"."),declaredDirectory=resolveContainedDirectory(directory,validator.working_directory);return Boolean(requestedDirectory&&declaredDirectory)&&requestedDirectory?.absolute===declaredDirectory?.absolute&&validator.command.length===check3.command.length&&validator.command.every((part,index)=>part===check3.command[index])}function isExactObligationContractAuthorization(directory,obligation,check3,provenance){let identity=obligation.validatorContract;if(!identity||check3.validator_contract?.path!==identity.path||check3.validator_contract.id!==identity.id)return!1;let validator=readTrustedRepositoryValidationContract(directory,identity.path,provenance)?.validators.find(({id})=>id===identity.id),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),validatorWorkspace=validator?resolveContainedDirectory(directory,validator.working_directory):void 0;if(!validator||validator.category!==obligation.category||validatorWorkspace?.absolute!==workspace?.absolute)return!1;if(!obligation.source.startsWith("package.json#")||!workspace)return!1;let scriptName=obligation.source.slice(13),packageText=readBoundedText(path321.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&declared.length===validator.command.length&&declared.every((part,index)=>part===validator.command[index])&&(packageManagerSelectsExactScript(check3.command,scriptName)||declared.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])))}catch{return!1}}function isSafeContractCommand(command){let executable=path321.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"");return!BLOCKED_EXECUTABLES.has(executable)&&!command.slice(1).some((arg)=>MUTATING_ARGUMENT.test(arg))&&!command.some((arg)=>/^(?:-h|--help|--version|help|version|--dry-run|--if-present)$/i.test(arg))&&!(["bun","node","python","python3","ruby","perl","npx"].includes(executable)&&command.slice(1).some((arg)=>["-e","--eval","-c","--call"].includes(arg)))}function isAllowedRepositoryExecutable(directory,workingDirectory,executable,contractValidated){if(!/[\\/]/.test(executable))return!0;if(path321.isAbsolute(executable))return!1;let workspace=resolveContainedDirectory(directory,workingDirectory);if(!workspace)return!1;let resolved=path321.resolve(workspace.absolute,executable),canonicalExecutable;try{canonicalExecutable=fs185.realpathSync(resolved)}catch{return!1}let canonicalRoot=(()=>{try{return fs185.realpathSync(path321.resolve(directory))}catch{return path321.resolve(directory)}})(),relative84=path321.relative(canonicalRoot,canonicalExecutable);if(relative84===".."||relative84.startsWith(`..${path321.sep}`)||path321.isAbsolute(relative84))return!1;let basename43=path321.basename(canonicalExecutable).toLowerCase().replace(/\.(?:cmd|bat|exe)$/,"");if(!contractValidated&&!["gradlew","mvnw"].includes(basename43))return!1;return fs185.statSync(canonicalExecutable).isFile()}function normalizedExecutable(command){return path321.basename(command[0]).toLowerCase().replace(/\.(?:exe|cmd|bat)$/,"")}function parseSimpleRepositoryScript(script){if(/[;&|><`\r\n]/.test(script)||script.includes("$(")||script.includes("${"))return;let tokens=script.match(/"(?:\\.|[^"\\])*"|'[^']*'|[^\s]+/g)?.map((token)=>{if(token.startsWith('"')&&token.endsWith('"')||token.startsWith("'")&&token.endsWith("'"))return token.slice(1,-1);return token})??[];return tokens.length>0?tokens:void 0}function packageManagerSelectedScriptName(command){let executable=normalizedExecutable(command);if(!["npm","bun","pnpm","yarn"].includes(executable))return;let positional=command.slice(1,command.indexOf("--")>=0?command.indexOf("--"):void 0).filter((arg)=>!arg.startsWith("-"));if(executable==="npm")return["run","run-script"].includes(positional[0]??"")?positional[1]:void 0;if(executable==="bun")return positional[0]==="run"?positional[1]:void 0;return positional[0]==="run"?positional[1]:positional[0]}function packageManagerSelectsExactScript(command,scriptName){return packageManagerSelectedScriptName(command)===scriptName}function isExactRepositoryPackageManagerScript(directory,workingDirectory,category,command){let scriptName=packageManagerSelectedScriptName(command),workspace=resolveContainedDirectory(directory,workingDirectory);if(!scriptName||!workspace||!categoryMatchesScriptName(category,scriptName))return!1;let packageText=readBoundedText(path321.join(workspace.absolute,"package.json"));if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared&&isPlausibleStageACommand(category,declared))}catch{return!1}}function commandMatchesObligationSource(directory,obligation,check3,contractValidated){let executable=normalizedExecutable(check3.command),effectiveExecutable=executable==="npx"&&check3.command[1]?path321.basename(check3.command[1]).toLowerCase():executable,source=obligation.source;if(source.includes(".pr-validation.json#")){let separator=source.lastIndexOf("#"),contractPath=source.slice(0,separator),validatorId=source.slice(separator+1);return contractValidated&&check3.validator_contract?.id===validatorId&&check3.validator_contract?.path.replaceAll("\\","/").replace(/^\.\//,"")===contractPath.replace(/^\.\//,"")}if(source.startsWith("package.json#")){let scriptName=source.slice(13),workspace=resolveContainedDirectory(directory,obligation.workingDirectory),packageText=workspace?readBoundedText(path321.join(workspace.absolute,"package.json")):void 0;if(!packageText)return!1;try{let script=JSON.parse(packageText).scripts?.[scriptName],declared=typeof script==="string"?parseSimpleRepositoryScript(script):void 0;return Boolean(declared)&&declared?.length===check3.command.length&&declared.every((part,index)=>part===check3.command[index])||packageManagerSelectsExactScript(check3.command,scriptName)}catch{return!1}}if(source==="Cargo.toml")return effectiveExecutable==="cargo";if(source==="go.mod")return effectiveExecutable==="go";if(source==="pom.xml")return["mvn","mvnw"].includes(effectiveExecutable);if(/^build\.gradle(?:\.kts)?$/.test(source))return["gradle","gradlew"].includes(effectiveExecutable);if(/^(?:Makefile|makefile)$/.test(source))return effectiveExecutable==="make";if(source==="CMakeLists.txt")return effectiveExecutable==="cmake";if(source==="Package.swift")return["swift","swiftc"].includes(effectiveExecutable);if(source==="setup.py"||source==="pyproject.toml#build-system")return["python","python3"].includes(effectiveExecutable);if(/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(source))return["dotnet","msbuild"].includes(effectiveExecutable);if(/\.(?:xcodeproj|xcworkspace)$/i.test(source))return effectiveExecutable==="xcodebuild";let sourceExecutables={"tsconfig.json":["tsc"],"pyrightconfig.json":["pyright"],".flowconfig":["flow"],"phpstan.neon":["phpstan"],"phpstan.neon.dist":["phpstan"],"psalm.xml":["psalm"],"psalm.xml.dist":["psalm"],"mypy.ini":["mypy"],"pyproject.toml#mypy":["mypy"],"biome.json":["biome"],"biome.jsonc":["biome"],"ruff.toml":["ruff"],".ruff.toml":["ruff"],"pyproject.toml#ruff":["ruff"],".rubocop.yml":["rubocop"],".swiftlint.yml":["swiftlint"],".golangci.yml":["golangci-lint"],".golangci.yaml":["golangci-lint"],".stylelintrc":["stylelint"],".stylelintrc.json":["stylelint"]};if(/^(?:\.eslintrc|eslint\.config\.)/.test(source))return effectiveExecutable==="eslint";return sourceExecutables[source]?.includes(effectiveExecutable)??!1}function discoverApplicableStageAObligations(directory,contractBase){let root=path321.resolve(directory),canonicalRoot=(()=>{try{return fs185.realpathSync(root)}catch{return root}})(),candidateRoots=[],seenRoots=new Set,discoveryOverflow,addCandidateRoot=(candidate2)=>{if(candidateRoots.length>=256){discoveryOverflow="Stage A repository discovery exceeded 256 contained workspace roots";return}try{if(!fs185.statSync(candidate2).isDirectory())return;let canonicalCandidate=fs185.realpathSync(candidate2),relative84=path321.relative(canonicalRoot,canonicalCandidate);if(relative84.startsWith(`..${path321.sep}`)||relative84===".."||path321.isAbsolute(relative84)||seenRoots.has(canonicalCandidate))return;seenRoots.add(canonicalCandidate),candidateRoots.push(canonicalCandidate)}catch{}},addWorkspacePattern=(pattern)=>{let normalized=pattern.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!normalized||normalized.startsWith("!")||path321.posix.isAbsolute(normalized)||normalized.split("/").includes("..")){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}if(!normalized.includes("*")){addCandidateRoot(path321.resolve(root,normalized));return}let wildcard=normalized.match(/^([^*?[\]]+)\/\*\/?$/);if(!wildcard){discoveryOverflow=`Stage A cannot safely expand declared workspace pattern "${pattern}"`;return}let container=path321.resolve(root,wildcard[1]);try{let entries=fs185.readdirSync(container,{withFileTypes:!0});if(entries.length>256){discoveryOverflow=`Stage A workspace container ${wildcard[1]} exceeds the 256-entry bounded discovery limit`;return}for(let entry of entries)if(entry.isDirectory())addCandidateRoot(path321.join(container,entry.name))}catch{}};addCandidateRoot(root);for(let containerName of["packages","apps","services","libs","crates"])addWorkspacePattern(`${containerName}/*`);let rootPackageText=readPresentRepositoryText(canonicalRoot,path321.join(root,"package.json"),"root package.json workspace declaration");if(rootPackageText)try{let value=JSON.parse(rootPackageText),workspacePatterns=Array.isArray(value.workspaces)?value.workspaces:value.workspaces?.packages;for(let pattern of workspacePatterns??[])if(typeof pattern==="string")addWorkspacePattern(pattern)}catch{discoveryOverflow="Stage A cannot safely inspect malformed root package.json workspace metadata"}let pnpmWorkspaceText=readPresentRepositoryText(canonicalRoot,path321.join(root,"pnpm-workspace.yaml"),"pnpm-workspace.yaml declaration");for(let match of pnpmWorkspaceText?.matchAll(/^\s*-\s*['"]?([^'"#\r\n]+?)['"]?\s*$/gm)??[])addWorkspacePattern(match[1]);let cargoMembers=readPresentRepositoryText(canonicalRoot,path321.join(root,"Cargo.toml"),"Cargo.toml workspace declaration")?.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/m)?.[1];for(let match of cargoMembers?.matchAll(/['"]([^'"]+)['"]/g)??[])addWorkspacePattern(match[1]);let mavenText=readPresentRepositoryText(canonicalRoot,path321.join(root,"pom.xml"),"pom.xml module declaration");for(let match of mavenText?.matchAll(/<module>\s*([^<]+?)\s*<\/module>/gi)??[])addWorkspacePattern(match[1]);let goWorkText=readPresentRepositoryText(canonicalRoot,path321.join(root,"go.work"),"go.work workspace declaration");for(let match of goWorkText?.matchAll(/^\s*(?:use\s+)?(\.\.?\/[^\s/]+(?:\/[^\s]+)*)\s*$/gm)??[])addWorkspacePattern(match[1]);for(let settingsName of["settings.gradle","settings.gradle.kts"]){let settingsText=readPresentRepositoryText(canonicalRoot,path321.join(root,settingsName),`${settingsName} workspace declaration`);for(let includeMatch of settingsText?.matchAll(/\binclude\s*\(?([^\r\n)]+)/g)??[])for(let projectMatch of includeMatch[1].matchAll(/['"]:?(.*?)['"]/g)){let projectPath=projectMatch[1].replaceAll(":","/");if(projectPath)addWorkspacePattern(projectPath)}}let obligations=new Map,addObligation=(category,candidateRoot,source,validatorContract)=>{let workspace=path321.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||".",id=`${category}:${workspace}:${source}`;if(!obligations.has(id)&&obligations.size>=256){discoveryOverflow="Stage A repository discovery exceeded 256 concrete validation obligations";return}obligations.set(id,{id,category,workingDirectory:workspace,source,...validatorContract?{validatorContract}:{}})},buildFiles=new Set(["Cargo.toml","go.mod","pom.xml","build.gradle","build.gradle.kts","Makefile","makefile","CMakeLists.txt","Package.swift","setup.py"]),typecheckFiles=new Set(["tsconfig.json","pyrightconfig.json",".flowconfig","phpstan.neon","phpstan.neon.dist","psalm.xml","psalm.xml.dist","mypy.ini"]),lintFiles=new Set(["biome.json","biome.jsonc",".eslintrc",".eslintrc.json",".eslintrc.yaml",".eslintrc.yml",".eslintrc.js",".eslintrc.cjs",".eslintrc.mjs","eslint.config.js","eslint.config.mjs","eslint.config.cjs","eslint.config.ts","ruff.toml",".ruff.toml",".rubocop.yml",".swiftlint.yml",".golangci.yml",".golangci.yaml",".stylelintrc",".stylelintrc.json"]);for(let candidateRoot of candidateRoots){let entries=[];try{if(entries=fs185.readdirSync(candidateRoot,{withFileTypes:!0}),entries.length>2048){discoveryOverflow=`Stage A workspace ${path321.relative(canonicalRoot,candidateRoot)||"."} exceeds the 2048-entry bounded manifest scan`;continue}}catch{continue}for(let entry of entries){if(entry.isFile()&&buildFiles.has(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isFile()&&typecheckFiles.has(entry.name))addObligation("typecheck",candidateRoot,entry.name);if(entry.isFile()&&lintFiles.has(entry.name))addObligation("lint",candidateRoot,entry.name);if(entry.isFile()&&/\.(?:sln|slnx|csproj|fsproj|vbproj)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name);if(entry.isDirectory()&&/\.(?:xcodeproj|xcworkspace)$/i.test(entry.name))addObligation("build",candidateRoot,entry.name)}let contractPath=path321.join(candidateRoot,".pr-validation.json"),contractRelative=path321.relative(canonicalRoot,contractPath).replaceAll("\\","/"),untrustedContract=readRepositoryValidationContract(canonicalRoot,contractRelative),contract=readTrustedRepositoryValidationContract(canonicalRoot,contractRelative,contractBase);if(fs185.existsSync(contractPath)&&!untrustedContract)discoveryOverflow=`Stage A found an invalid, oversized, unreadable, or escaping validation contract at ${contractRelative}`;else if(untrustedContract&&!contract)discoveryOverflow=`Stage A validation contract at ${contractRelative} must be unchanged from the immutable merge base named by base_ref and base_sha`;let contractValidatorsCoveredByScripts=new Set,packageText=readPresentRepositoryText(canonicalRoot,path321.join(candidateRoot,"package.json"),`${path321.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json manifest`);if(packageText)try{let value=JSON.parse(packageText);for(let[script,commandText]of Object.entries(value.scripts??{})){let declaredCommand=typeof commandText==="string"?parseSimpleRepositoryScript(commandText):void 0;for(let category of OPTIONAL_STAGE_A_CATEGORIES){if(!categoryMatchesScriptName(category,script))continue;let authorizingValidator=contract?.validators.find((validator)=>{let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);return validator.category===category&&validatorWorkspace?.absolute===candidateRoot&&(!declaredCommand||declaredCommand.length===validator.command.length&&declaredCommand.every((part,index)=>part===validator.command[index]))});if(!declaredCommand){if(!authorizingValidator)discoveryOverflow=`Stage A opaque package script ${path321.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json#${script} requires a trusted base-identical contract validator for ${category}`;continue}if(isPlausibleStageACommand(category,declaredCommand)||Boolean(authorizingValidator)){if(addObligation(category,candidateRoot,`package.json#${script}`,authorizingValidator?{path:contractRelative,id:authorizingValidator.id}:void 0),authorizingValidator)contractValidatorsCoveredByScripts.add(authorizingValidator.id)}}}}catch{discoveryOverflow=`Stage A cannot safely inspect malformed package manifest at ${path321.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/package.json`}let pyprojectText=readPresentRepositoryText(canonicalRoot,path321.join(candidateRoot,"pyproject.toml"),`${path321.relative(canonicalRoot,candidateRoot).replaceAll("\\","/")||"."}/pyproject.toml manifest`);if(pyprojectText?.match(/\[build-system\]/i))addObligation("build",candidateRoot,"pyproject.toml#build-system");if(pyprojectText?.match(/\[(?:tool\.)?mypy\]/i))addObligation("typecheck",candidateRoot,"pyproject.toml#mypy");if(pyprojectText?.match(/\[tool\.ruff(?:\.|\])/i))addObligation("lint",candidateRoot,"pyproject.toml#ruff");for(let validator of contract?.validators??[]){if(contractValidatorsCoveredByScripts.has(validator.id))continue;if(OPTIONAL_STAGE_A_CATEGORIES.includes(validator.category)){let validatorWorkspace=resolveContainedDirectory(canonicalRoot,validator.working_directory);if(!validatorWorkspace)continue;addObligation(validator.category,validatorWorkspace.absolute,`${contractRelative}#${validator.id}`)}}}if(discoveryOverflow)throw Error(`BLOCKED: ${discoveryOverflow}`);return[...obligations.values()]}function discoverApplicableStageACategories(directory,contractBase){let applicable=new Set(discoverApplicableStageAObligations(directory,contractBase).map(({category})=>category));return OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicable.has(category))}async function executeRunPrFeedbackStageA(args2,directory,context={}){let parsed=RunPrFeedbackStageAArgsSchema.safeParse(args2);if(!parsed.success)return failure2(`Invalid PR-feedback Stage A request: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);if(!context.sessionID?.trim())return failure2("PR-feedback Stage A requires an active sessionID");let categories=parsed.data.checks.map((check3)=>check3.category);for(let requiredSingleton of ALWAYS_REQUIRED_CATEGORIES)if(categories.filter((category)=>category===requiredSingleton).length!==1)return failure2(`Stage A requires exactly one ${requiredSingleton} receipt`);let contractBase;try{contractBase=await resolveContractBaseProvenance(directory,parsed.data.pr_head_sha,parsed.data.base_ref,parsed.data.base_sha)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableObligations;try{applicableObligations=_internals253.discoverApplicableStageAObligations(directory,contractBase)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}let applicableCategories=OPTIONAL_STAGE_A_CATEGORIES.filter((category)=>applicableObligations.some((obligation)=>obligation.category===category)),matchedObligationIds=new Set,selectedObligations=new Map,normalizedCheckDirectories=new Map;for(let check3 of parsed.data.checks){let workspace=resolveContainedDirectory(directory,check3.working_directory??".");if(!workspace)return failure2(`Stage A ${check3.category} working_directory is not a contained repository workspace`);if(normalizedCheckDirectories.set(check3,workspace.relative),!OPTIONAL_STAGE_A_CATEGORIES.includes(check3.category))continue;let candidates=applicableObligations.filter((obligation)=>obligation.category===check3.category&&obligation.workingDirectory===workspace.relative);if(candidates.length===0&&!check3.obligation_id)continue;let selected=check3.obligation_id?candidates.find((candidate2)=>candidate2.id===check3.obligation_id):candidates.length===1?candidates[0]:void 0;if(!selected)return failure2(`Stage A ${check3.category} must name one exact discovered obligation_id for workspace ${workspace.relative}: ${candidates.map(({id})=>id).join(", ")||"none discovered"}`);if(matchedObligationIds.has(selected.id))return failure2(`Stage A repeats discovered obligation ${selected.id}`);matchedObligationIds.add(selected.id),selectedObligations.set(check3,selected),check3.obligation_id=selected.id,check3.working_directory=workspace.relative}let missingObligations=applicableObligations.filter(({id})=>!matchedObligationIds.has(id));if(missingObligations.length>0)return failure2(`Stage A is missing concrete repository validation obligations: ${missingObligations.map(({id})=>id).join(", ")}`);let diffCheck=parsed.data.checks.find((check3)=>check3.category==="diff-check");if(!diffCheck||!isExactDiffCheck(diffCheck.command))return failure2('Stage A diff-check must execute array-form ["git", "diff", "--check"]');for(let check3 of parsed.data.checks){let directContractValidated=isExactRepositoryContractValidator(directory,check3,contractBase),selectedObligation=selectedObligations.get(check3),obligationContractValidated=selectedObligation?isExactObligationContractAuthorization(directory,selectedObligation,check3,contractBase):!1,contractValidated=directContractValidated||obligationContractValidated;if(selectedObligation?.validatorContract&&!obligationContractValidated)return failure2(`Stage A obligation ${selectedObligation.id} requires exact validator_contract ${selectedObligation.validatorContract.path}#${selectedObligation.validatorContract.id}`);let executable=normalizedExecutable(check3.command);if(selectedObligation&&!commandMatchesObligationSource(directory,selectedObligation,check3,contractValidated))return failure2(`Stage A command does not prove its exact source obligation ${selectedObligation.id}`);if(!isPlausibleStageACommand(check3.category,check3.command)&&!(contractValidated&&isSafeContractCommand(check3.command)))return failure2(`Stage A ${check3.category} command is not a recognized non-publishing ${check3.category} validation command`);let isPackageManagerCommand=["npm","pnpm","yarn"].includes(executable)||executable==="bun"&&check3.command[1]==="run";if(!selectedObligation&&isPackageManagerCommand&&(check3.category!=="reproduction"||!isExactRepositoryPackageManagerScript(directory,normalizedCheckDirectories.get(check3)??".",check3.category,check3.command)))return failure2(`Stage A ${check3.category} package-manager command must select one exact inspected repository script`);if(!isAllowedRepositoryExecutable(directory,normalizedCheckDirectories.get(check3)??".",check3.command[0],contractValidated))return failure2(`Stage A rejects escaping or undeclared repository wrapper executables: ${check3.command[0]}`)}let normalizedCommands=parsed.data.checks.map((check3)=>`${check3.obligation_id??check3.category}\x00${normalizedCheckDirectories.get(check3)??"."}\x00${check3.command.join("\x00")}`.toLowerCase());if(new Set(normalizedCommands).size!==normalizedCommands.length)return failure2("Stage A categories require distinct commands; one command cannot prove multiple obligations");let reproduction=parsed.data.checks.find((check3)=>check3.category==="reproduction");if(!reproduction?.targets?.length)return failure2("Stage A reproduction requires at least one explicit test/regression target");let reproductionSelectors=reproductionSelectorValues(reproduction.command),missingTargets=reproduction.targets.filter((target)=>![...reproductionSelectors].some((selector)=>selector===target||selector.replaceAll("\\","/")===target.replaceAll("\\","/")));if(missingTargets.length>0)return failure2(`Stage A reproduction command does not select declared target(s): ${missingTargets.join(", ")}`);for(let target of reproduction.targets){if(!/[\\/]/.test(target))continue;let pathTarget=target.split("::",1)[0].replace(/:\d+(?::\d+)?$/,""),resolved=path321.resolve(directory,pathTarget),relative84=path321.relative(path321.resolve(directory),resolved);if(!relative84||relative84.startsWith("..")||path321.isAbsolute(relative84)||!fs185.existsSync(resolved)||!fs185.statSync(resolved).isFile())return failure2(`Stage A reproduction target is not a contained existing file: ${target}`)}try{let state=await assertPrFeedbackVerificationSettled(directory,context.sessionID),feedbackTargets=reproduction.feedback_targets??[],mappedFeedbackIds=feedbackTargets.map((mapping)=>mapping.feedback_item_id);if(mappedFeedbackIds.length!==new Set(mappedFeedbackIds).size||mappedFeedbackIds.length!==(state.prFeedbackInventory?.length??0)||!mappedFeedbackIds.every((itemId,index)=>itemId===state.prFeedbackInventory?.[index])||feedbackTargets.some((mapping)=>!reproduction.targets?.includes(mapping.target)))return failure2("Stage A reproduction requires one exact target and expected-behavior mapping for every immutable feedback item in declared order");if(state.prHeadSha!==parsed.data.pr_head_sha)return failure2(`PR_FEEDBACK head mismatch: expected ${state.prHeadSha??"(unbound)"}, received ${parsed.data.pr_head_sha}`);await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,"PR_FEEDBACK");let beforeDigest=await _internals253.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!beforeDigest)return failure2("Could not compute a bounded Stage A revision digest");let boundHead=(await _internals253.resolveCurrentGitHeadAsync(directory))?.trim(),boundControlState=await _internals253.resolveGitControlStateDigestAsync(directory);if(!boundHead||!boundControlState)return failure2("Could not bind Stage A to the current Git HEAD, refs, config, and index state");let results=[],receipts=[];for(let check3 of parsed.data.checks){let commandRevision=await _internals253.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),commandControl=await _internals253.resolveGitControlStateDigestAsync(directory);if(commandRevision!==beforeDigest||commandControl!==boundControlState||(await _internals253.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A Git or content state changed before ${check3.category}; restart the complete sequence`,results,directory,context.sessionID);let started=Date.now(),[executable,...commandArgs]=check3.command,checkDirectory=resolveContainedDirectory(directory,check3.working_directory??".");if(!checkDirectory)return failure2(`Stage A ${check3.category} workspace disappeared before execution`,results,directory,context.sessionID);let result;try{result=await _internals253.runExternalTool({executable,args:commandArgs,cwd:checkDirectory.absolute,timeoutMs:check3.timeout_ms??120000,maxStdoutBytes:MAX_OUTPUT_BYTES9,maxStderrBytes:MAX_OUTPUT_BYTES9})}catch(error93){let afterThrowRevision=await _internals253.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterThrowControl=await _internals253.resolveGitControlStateDigestAsync(directory);if(afterThrowRevision!==beforeDigest||afterThrowControl!==boundControlState||(await _internals253.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} threw after mutating content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);return failure2(`Stage A ${check3.category} execution threw: ${error93 instanceof Error?error93.message:String(error93)}`,results,directory,context.sessionID)}let durationMs=Date.now()-started;results.push({category:check3.category,working_directory:checkDirectory.relative,...check3.obligation_id?{obligation_id:check3.obligation_id}:{},command:check3.command,status:result.status,exit_code:result.exitCode,duration_ms:durationMs,stdout:result.stdout,stderr:result.stderr,stdout_truncated:result.stdoutTruncated,stderr_truncated:result.stderrTruncated,...result.message?{message:result.message}:{}});let afterCommandRevision=await _internals253.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha),afterCommandControl=await _internals253.resolveGitControlStateDigestAsync(directory);if(afterCommandRevision!==beforeDigest||afterCommandControl!==boundControlState||(await _internals253.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2(`Stage A ${check3.category} mutated content, HEAD, refs, Git config, or index state`,results,directory,context.sessionID);if(result.status!=="completed"||result.exitCode!==0)return failure2(`Stage A ${check3.category} failed (${result.status}, exit ${result.exitCode??"unknown"})`,results,directory,context.sessionID);if(check3.validator_contract&&!`${result.stdout}
|
|
7120
7120
|
${result.stderr}`.trim())return failure2(`Stage A repository-contract validator ${check3.validator_contract.id} produced no machine-observable evidence`,results,directory,context.sessionID);if(check3.category==="reproduction"&&outputReportsZeroTests(result))return failure2("Stage A reproduction produced truncated proof or reported that zero tests executed",results,directory,context.sessionID);if(check3.category==="reproduction"&&!`${result.stdout}
|
|
7121
7121
|
${result.stderr}`.trim())return failure2("Stage A reproduction produced no machine-observable execution evidence",results,directory,context.sessionID);receipts.push({category:check3.category,workingDirectory:checkDirectory.relative,...check3.obligation_id?{obligationId:check3.obligation_id}:{},...check3.validator_contract?{validatorContract:{path:check3.validator_contract.path,id:check3.validator_contract.id}}:{},command:check3.command,...check3.targets?{targets:check3.targets}:{},...check3.feedback_targets?{feedbackTargets:check3.feedback_targets.map((mapping)=>({feedbackItemId:mapping.feedback_item_id,target:mapping.target,expectedBehavior:mapping.expected_behavior,proofKind:mapping.proof_kind}))}:{},durationMs})}let afterDigest=await _internals253.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha);if(!afterDigest||afterDigest!==beforeDigest)return failure2("Stage A changed the working-tree revision; rerun all Stage A checks on the resulting diff",results,directory,context.sessionID);if(await _internals253.resolveGitControlStateDigestAsync(directory)!==boundControlState||(await _internals253.resolveCurrentGitHeadAsync(directory))?.trim()!==boundHead)return failure2("Stage A changed HEAD, refs, Git config, or index state; rerun the complete sequence",results,directory,context.sessionID);await recordPrFeedbackStageA(directory,context.sessionID,afterDigest,receipts,{applicableCategories,applicableObligations});let successPayload={success:!0,pr_head_sha:parsed.data.pr_head_sha,revision_digest:afterDigest,checks:results.map(summarizeCheckEntry)};return JSON.stringify(successPayload,null,2)}catch(error93){return failure2(error93 instanceof Error?error93.message:String(error93))}}var _internals253={runExternalTool,storeSummary,readGitTextAtRevision,resolveExactMergeBase,resolveExactMergeBaseAsync,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveGitControlStateDigest,resolveGitControlStateDigestAsync,resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,isPlausibleStageACommand,discoverApplicableStageACategories,discoverApplicableStageAObligations,commandMatchesObligationSource},run_pr_feedback_stage_a=createSwarmTool({description:"Execute and persist mandatory PR-feedback Stage A diff-check and targeted reproduction receipts plus every build, typecheck, or lint check mechanically applicable to this repository, on one content-bound revision.",args:{pr_head_sha:RunPrFeedbackStageAArgsSchema.shape.pr_head_sha,checks:RunPrFeedbackStageAArgsSchema.shape.checks},execute:executeRunPrFeedbackStageA});init_sast_scan();init_zod();init_plan_schema();init_qa_gate_profile();init_file_locks();import*as fs186 from"node:fs";import*as path322 from"node:path";init_ledger();init_manager();init_planning_profile();init_utils3();init_scope_binding();init_effective_spec();init_project_boundary();init_create_tool();function executionProfilesEqual(a,b){return a.parallelization_enabled===b.parallelization_enabled&&a.max_concurrent_tasks===b.max_concurrent_tasks&&a.council_parallel===b.council_parallel&&a.locked===b.locked&&a.auto_proceed===b.auto_proceed&&a.commit_after_each_completed_task===b.commit_after_each_completed_task&&a.planning_profile===b.planning_profile}function isLedgerProjectionReconcileRequest(args2){return args2.reconcile_ledger_projection===!0}function isPureLedgerProjectionReconcileRequest(args2){return isLedgerProjectionReconcileRequest(args2)&&args2.reset_statuses!==!0&&(args2.removed_task_ids?.length??0)===0&&(args2.removal_reason?.trim().length??0)===0&&args2.confirm_destructive_reset!==!0&&args2.confirm_identity_change!==!0&&args2.confirm_requirement_coverage_gaps!==!0}function derivePhaseStatusesForComparison(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((task2)=>task2.status==="completed"))phase.status="complete";else if(tasks.some((task2)=>task2.status==="in_progress"))phase.status="in_progress";else if(tasks.some((task2)=>task2.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function normalizePlanForReconcileComparison(plan){return{schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:plan.execution_profile?{parallelization_enabled:plan.execution_profile.parallelization_enabled,max_concurrent_tasks:plan.execution_profile.max_concurrent_tasks,council_parallel:plan.execution_profile.council_parallel,locked:plan.execution_profile.locked,auto_proceed:plan.execution_profile.auto_proceed,commit_after_each_completed_task:plan.execution_profile.commit_after_each_completed_task,...plan.execution_profile.planning_profile!==void 0?{planning_profile:plan.execution_profile.planning_profile}:{}}:void 0,phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task2)=>({id:task2.id,phase:task2.phase,status:task2.status,size:task2.size,description:task2.description,depends:task2.depends,acceptance:task2.acceptance,files_touched:task2.files_touched,fr_refs:task2.fr_refs}))}))}}async function readLedgerTailCapture(directory){let events=await readLedgerEvents(directory),tail2=events[events.length-1];if(!tail2)return null;return{seq:tail2.seq,plan_hash_after:tail2.plan_hash_after}}function materializeResolvedExecutionProfile(profile,persistedPlanningProfile){if(persistedPlanningProfile===void 0){let{planning_profile:_planningProfile,...withoutPlanningProfile}=profile;return withoutPlanningProfile}return{...profile,planning_profile:persistedPlanningProfile}}function canRatchetLockedPlanningProfile(existingProfile,requestedProfile){return existingProfile.planning_profile==="balanced"&&requestedProfile.planning_profile==="strict"&&existingProfile.parallelization_enabled===requestedProfile.parallelization_enabled&&existingProfile.max_concurrent_tasks===requestedProfile.max_concurrent_tasks&&existingProfile.council_parallel===requestedProfile.council_parallel&&existingProfile.locked===requestedProfile.locked&&existingProfile.auto_proceed===requestedProfile.auto_proceed&&existingProfile.commit_after_each_completed_task===requestedProfile.commit_after_each_completed_task}function evaluateRequirementCoverage(specContent,args2){if(!specContent)return null;let requirements=extractRequirements(specContent);if(requirements.length===0)return null;let covered=[],missing=[];for(let requirement of requirements){let mappedTaskIds=[],idPattern=new RegExp(`\\b${requirement.id}\\b`,"i");for(let phase of args2.phases)for(let task2 of phase.tasks){let taskText=`${task2.description}
|
|
7122
|
-
${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task2.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task2.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task2 of phase.tasks)if(placeholderPattern.test(task2.description.trim()))issues.push(`Task ${task2.id} description appears to be a template placeholder: "${task2.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task2 of phase.tasks)if(!taskIdPattern.test(task2.id))validationErrors.push(`Task '${task2.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};try{assertProjectRoot(targetWorkspace)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],recovery_guidance:"Pass the project root, or add an explicit local .git/.opencode project boundary before retrying save_plan."}}if(args2.working_directory&&fallbackDir){let resolvedTarget=path322.resolve(args2.working_directory),resolvedRoot=path322.resolve(fallbackDir),fallbackExists=!1;try{fs186.accessSync(resolvedRoot,fs186.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedTarget,resolvedRoot)){if(!hasExplicitProjectBoundary(resolvedTarget))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}}let dir=targetWorkspace,reconcileLedgerProjection=isLedgerProjectionReconcileRequest(args2);if(reconcileLedgerProjection&&!isPureLedgerProjectionReconcileRequest(args2))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_INVALID: reconcile_ledger_projection only permits an unchanged semantic re-save.",errors:["Remove reset_statuses, task-removal acknowledgements, identity overrides, and requirement-coverage overrides before retrying reconcile_ledger_projection."],recovery_guidance:"Retry with reconcile_ledger_projection: true only when save_plan is re-saving the same identity, task graph, statuses, and execution_profile to reconverge a stale projection."};let existingStatusMap=new Map,existingFilesMap=new Map,priorTaskIds=new Set,preservedExecutionProfile,existingPlan=null;try{existingPlan=await loadPlanJsonOnly(dir)}catch{}if(existingPlan){for(let phase of existingPlan.phases)for(let task2 of phase.tasks)priorTaskIds.add(task2.id),existingFilesMap.set(task2.id,[...task2.files_touched]);if(!args2.reset_statuses)for(let phase of existingPlan.phases)for(let task2 of phase.tasks)existingStatusMap.set(task2.id,task2.status);preservedExecutionProfile=existingPlan.execution_profile}let reconcileLedgerTailCapture=reconcileLedgerProjection?await readLedgerTailCapture(dir).catch(()=>null):null,specMtime=reconcileLedgerProjection?existingPlan?.specMtime:void 0,specHash=reconcileLedgerProjection?existingPlan?.specHash:void 0,specContent,planningProfileResolution=resolvePlanningProfile({directory:dir,incomingExecutionProfile:args2.execution_profile,existingExecutionProfile:preservedExecutionProfile,resetStatuses:args2.reset_statuses}),effectivePlanningProfile=planningProfileResolution.effective,persistedPlanningProfile=planningProfileResolution.persisted;if(existingPlan?.execution_profile?.locked&&args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existingPlan.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};let requestedMaterializedProfile=materializeResolvedExecutionProfile(requestedProfile.data,persistedPlanningProfile);if(executionProfilesEqual(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=existingPlan.execution_profile;else if(canRatchetLockedPlanningProfile(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=requestedMaterializedProfile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — only a balanced→strict planning_profile ratchet is allowed without reset_statuses. All other profile changes are rejected."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec&&effectivePlanningProfile==="strict")return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};if(spec){specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path322.join(targetWorkspace,".swarm","spec-snapshot.md");await fs186.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let profileLookup;try{profileLookup=getProfileLookupForIdentity(targetWorkspace,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not verify the durable QA gate selection.",errors:[error93 instanceof Error?`QA gate profile store read failed: ${error93.message}`:"QA gate profile store read failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry get_qa_gate_profile and save_plan with the same swarm_id and title."}}if(profileLookup.kind==="missing")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not create the default balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile bootstrap failed: ${error93.message}`:"QA gate profile bootstrap failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",errors:["No QA gate profile found for the exact plan identity"],recovery_guidance:`Present the PLAN gate dialogue, then call set_qa_gates with swarm_id=${JSON.stringify(args2.swarm_id)} and plan_title=${JSON.stringify(args2.title)} before retrying save_plan with the identical identity.`};else if(profileLookup.kind==="unbound_legacy")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not exact-bind the balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile exact-bind failed: ${error93.message}`:"QA gate profile exact-bind failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",errors:["QA gate profile exists for the readable plan id, but no exact swarm_id/plan_title binding has been adopted yet."],recovery_guidance:formatLegacyQaBindingRecovery({swarm:args2.swarm_id,title:args2.title},"retry save_plan with the identical identity")}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(!reconcileLedgerProjection&&requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};{let existing=existingPlan;if(existing){if(args2.confirm_identity_change!==!0){if(!(existing.swarm===args2.swarm_id&&existing.title===args2.title)){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}}}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??(args2.execution_profile.parallelization_enabled===void 0?{parallelization_enabled:!0}:{}),...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};resolvedProfile=materializeResolvedExecutionProfile(parsed.data,persistedPlanningProfile)}if(resolvedProfile===void 0)resolvedProfile={...ExecutionProfileSchema.parse({}),parallelization_enabled:!0,...persistedPlanningProfile!==void 0?{planning_profile:persistedPlanningProfile}:{}};else if(resolvedProfile.planning_profile===void 0&&persistedPlanningProfile!==void 0)resolvedProfile={...resolvedProfile,planning_profile:persistedPlanningProfile};let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task2 of phase.tasks)incomingTaskIds.add(task2.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let resolvedFilesByTask=new Map;for(let phase of args2.phases)for(let task2 of phase.tasks){if(task2.files_touched===void 0){resolvedFilesByTask.set(task2.id,existingFilesMap.get(task2.id)??[]);continue}if(task2.files_touched.length===0){resolvedFilesByTask.set(task2.id,[]);continue}let normalized=normalizeScopeFiles(task2.files_touched);if(!normalized)return{success:!1,message:"PLAN_TASK_SCOPE_INVALID: files_touched must contain valid project-relative paths",errors:[`Task "${task2.id}" has an invalid files_touched list. Absolute paths, traversal, empty entries, and control characters are not allowed.`],recovery_guidance:"Retry save_plan with normalized project-relative paths, omit files_touched to preserve the prior task scope, or pass [] to clear it explicitly."};resolvedFilesByTask.set(task2.id,normalized)}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:reconcileLedgerProjection?existingPlan?.migration_status:"native",current_phase:reconcileLedgerProjection?existingPlan?.current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{let existingPhase=reconcileLedgerProjection?existingPlan?.phases.find((candidate2)=>candidate2.id===phase.id):void 0;return{id:phase.id,name:phase.name,status:"pending",type:existingPhase?.type,required_agents:existingPhase?.required_agents?[...existingPhase.required_agents]:void 0,tasks:phase.tasks.map((task2)=>{let existingTask=existingPhase?.tasks.find((candidate2)=>candidate2.id===task2.id);return{id:task2.id,phase:phase.id,status:existingStatusMap.get(task2.id)??"pending",size:task2.size??existingTask?.size??"small",description:task2.description,depends:task2.depends??existingTask?.depends??[],acceptance:task2.acceptance??existingTask?.acceptance,files_touched:resolvedFilesByTask.get(task2.id)??[],evidence_path:existingTask?.evidence_path,blocked_reason:existingTask?.blocked_reason,fr_refs:task2.fr_refs??existingTask?.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{if(reconcileLedgerProjection){let lockedRuntimePlan=await loadPlan(dir).catch(()=>null);if(lockedRuntimePlan?._ledgerReplayStale!==!0)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_NOT_STALE: reconcile_ledger_projection is only allowed when loadPlan reports a stale projection.",errors:[lockedRuntimePlan?"The current plan projection is not marked _ledgerReplayStale.":"The current plan could not be loaded for stale-projection reconciliation."],recovery_guidance:"Use reconcile_ledger_projection only to reconverge a workspace whose plan.json still hash-mismatches the ledger after replay failure."};let lockedTailCapture=await readLedgerTailCapture(dir).catch(()=>null);if(reconcileLedgerTailCapture===null||lockedTailCapture===null||reconcileLedgerTailCapture.seq!==lockedTailCapture.seq||reconcileLedgerTailCapture.plan_hash_after!==lockedTailCapture.plan_hash_after)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_STALE: the ledger tail changed before save_plan acquired the lock.",errors:["Re-read the stale plan and retry reconcile_ledger_projection against the latest ledger tail."],recovery_guidance:"Retry reconcile_ledger_projection only when the incoming plan still matches the current stale projection exactly."};let comparableIncomingPlan=PlanSchema.parse(JSON.parse(JSON.stringify(plan)));derivePhaseStatusesForComparison(comparableIncomingPlan);let comparableLoadedPlan=PlanSchema.parse(lockedRuntimePlan);if(JSON.stringify(normalizePlanForReconcileComparison(comparableIncomingPlan))!==JSON.stringify(normalizePlanForReconcileComparison(comparableLoadedPlan)))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_MISMATCH: reconcile_ledger_projection may not change plan semantics.",errors:["Incoming save_plan content does not exactly match the loaded stale projection (identity, task graph, statuses, or execution_profile changed)."],recovery_guidance:"Remove semantic edits and retry reconcile_ledger_projection with the exact stale plan content, or retry save_plan without reconcile_ledger_projection for a normal plan revision."}}await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,planLockAlreadyHeld:!0,...reconcileLedgerProjection&&reconcileLedgerTailCapture?{staleProjectionReconcile:{expectedSeq:reconcileLedgerTailCapture.seq,expectedLedgerHash:reconcileLedgerTailCapture.plan_hash_after}}:{},...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}});let savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path322.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs186.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[];if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path322.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate (default: small)"),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),files_touched:exports_external.array(exports_external.string()).max(1e4).optional().describe("Exact project-relative files or directories this task may modify. Omit on revision to preserve the prior scope; pass [] to clear it explicitly."),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false."),commit_after_each_completed_task:exports_external.boolean().optional().describe("When true, execution creates a checkpoint commit after each successfully completed task. Default false."),planning_profile:exports_external.enum(["balanced","strict"]).optional().describe("Planning-policy profile. balanced auto-seeds durable defaults and minimizes ceremony; strict requires the full QA questionnaire and an effective spec.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile."),reconcile_ledger_projection:exports_external.boolean().optional().describe("Narrow stale-ledger recovery mode. When true, save_plan only permits an unchanged semantic re-save that reconverges a _ledgerReplayStale plan.json with the authoritative ledger.")},execute:async(args2,_directory)=>{return JSON.stringify(await executeSavePlan(args2,_directory),null,2)}});init_zod();init_manager2();import*as fs187 from"node:fs";import*as path323 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
|
|
7122
|
+
${task2.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=task2.fr_refs?.includes(requirement.id)??!1;if(matchesFreeText||matchesFrRefs)mappedTaskIds.push(task2.id)}let entry={id:requirement.id,obligation:requirement.obligation,text:requirement.text,mapped_task_ids:mappedTaskIds};if(mappedTaskIds.length>0)covered.push(entry);else missing.push(entry)}let blockingMissing=missing.filter((entry)=>entry.obligation==="MUST"||entry.obligation==="SHALL");return{status:blockingMissing.length>0?args2.confirm_requirement_coverage_gaps===!0?"override":"failed":"passed",total_requirements:requirements.length,covered_count:covered.length,missing_count:missing.length,blocking_missing_count:blockingMissing.length,covered,missing,blocking_missing:blockingMissing}}function detectPlaceholderContent(args2){let issues=[],placeholderPattern=/^\[\w[\w\s]*\]$/;if(placeholderPattern.test(args2.title.trim()))issues.push(`Plan title appears to be a template placeholder: "${args2.title}"`);for(let phase of args2.phases){if(placeholderPattern.test(phase.name.trim()))issues.push(`Phase ${phase.id} name appears to be a template placeholder: "${phase.name}"`);for(let task2 of phase.tasks)if(placeholderPattern.test(task2.description.trim()))issues.push(`Task ${task2.id} description appears to be a template placeholder: "${task2.description}"`)}return issues}function validateTargetWorkspace(target,source){if(target===void 0||target===null)return`Target workspace is required: ${source} not provided`;let trimmed=target.trim();if(trimmed.length===0)return`Target workspace cannot be empty or whitespace: ${source}`;if(trimmed.replace(/\\/g,"/").includes(".."))return`Target workspace cannot contain path traversal: ${source} contains ".."`;return}async function executeSavePlan(args2,fallbackDir){let validationErrors=[];for(let phase of args2.phases){if(!Number.isInteger(phase.id)||phase.id<=0)validationErrors.push(`Phase ${phase.id} has invalid id: must be a positive integer`);let taskIdPattern=/^\d+\.\d+(\.\d+)*$/;for(let task2 of phase.tasks)if(!taskIdPattern.test(task2.id))validationErrors.push(`Task '${task2.id}' in phase ${phase.id} has invalid id format: must match N.M pattern (e.g. '1.1', '2.3')`)}if(validationErrors.length>0)return{success:!1,message:"Plan rejected: invalid phase or task IDs",errors:validationErrors,recovery_guidance:'Phase IDs must be positive integers: 1, 2, 3 (not 0, -1, or decimals). Task IDs must use N.M format: "1.1", "2.3", "3.1". Call save_plan again with corrected ids. Never write .swarm/plan.json or .swarm/plan.md directly.'};let placeholderIssues=detectPlaceholderContent(args2);if(placeholderIssues.length>0)return{success:!1,message:"Plan rejected: contains template placeholder content",errors:placeholderIssues,recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};let targetWorkspace=args2.working_directory??fallbackDir,workspaceError=validateTargetWorkspace(targetWorkspace,args2.working_directory?"working_directory":"fallbackDir");if(workspaceError)return{success:!1,message:"Target workspace validation failed: provide working_directory parameter to save_plan",errors:[workspaceError],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."};try{assertProjectRoot(targetWorkspace)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],recovery_guidance:"Pass the project root, or add an explicit local .git/.opencode project boundary before retrying save_plan."}}if(args2.working_directory&&fallbackDir){let resolvedTarget=path322.resolve(args2.working_directory),resolvedRoot=path322.resolve(fallbackDir),fallbackExists=!1;try{fs186.accessSync(resolvedRoot,fs186.constants.F_OK),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedTarget,resolvedRoot)){if(!hasExplicitProjectBoundary(resolvedTarget))return{success:!1,message:`working_directory must be the project root. Got "${args2.working_directory}" (resolves to "${resolvedTarget}"), which is a subdirectory of fallback "${resolvedRoot}". Omit working_directory or pass the project root explicitly.`,errors:[`working_directory "${resolvedTarget}" is a subdirectory of fallback "${resolvedRoot}"`],recovery_guidance:`Pass working_directory: "${resolvedRoot}" or omit the field entirely.`}}}}let dir=targetWorkspace,reconcileLedgerProjection=isLedgerProjectionReconcileRequest(args2);if(reconcileLedgerProjection&&!isPureLedgerProjectionReconcileRequest(args2))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_INVALID: reconcile_ledger_projection only permits an unchanged semantic re-save.",errors:["Remove reset_statuses, task-removal acknowledgements, identity overrides, and requirement-coverage overrides before retrying reconcile_ledger_projection."],recovery_guidance:"Retry with reconcile_ledger_projection: true only when save_plan is re-saving the same identity, task graph, statuses, and execution_profile to reconverge a stale projection."};let existingStatusMap=new Map,existingFilesMap=new Map,priorTaskIds=new Set,preservedExecutionProfile,existingPlan=null;try{existingPlan=await loadPlanJsonOnly(dir)}catch{}if(existingPlan){for(let phase of existingPlan.phases)for(let task2 of phase.tasks)priorTaskIds.add(task2.id),existingFilesMap.set(task2.id,[...task2.files_touched]);if(!args2.reset_statuses)for(let phase of existingPlan.phases)for(let task2 of phase.tasks)existingStatusMap.set(task2.id,task2.status);preservedExecutionProfile=existingPlan.execution_profile}let reconcileLedgerTailCapture=reconcileLedgerProjection?await readLedgerTailCapture(dir).catch(()=>null):null,specMtime=reconcileLedgerProjection?existingPlan?.specMtime:void 0,specHash=reconcileLedgerProjection?existingPlan?.specHash:void 0,specContent,planningProfileResolution=resolvePlanningProfile({directory:dir,incomingExecutionProfile:args2.execution_profile,existingExecutionProfile:preservedExecutionProfile,resetStatuses:args2.reset_statuses}),effectivePlanningProfile=planningProfileResolution.effective,persistedPlanningProfile=planningProfileResolution.persisted;if(existingPlan?.execution_profile?.locked&&args2.execution_profile!==void 0&&!args2.reset_statuses){let requestedProfile=ExecutionProfileSchema.safeParse({...existingPlan.execution_profile,...args2.execution_profile});if(!requestedProfile.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:requestedProfile.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};let requestedMaterializedProfile=materializeResolvedExecutionProfile(requestedProfile.data,persistedPlanningProfile);if(executionProfilesEqual(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=existingPlan.execution_profile;else if(canRatchetLockedPlanningProfile(existingPlan.execution_profile,requestedMaterializedProfile))preservedExecutionProfile=requestedMaterializedProfile;else return{success:!1,message:"EXECUTION_PROFILE_LOCKED: The execution_profile for this plan is locked and cannot be changed.",errors:["execution_profile.locked is true — only a balanced→strict planning_profile ratchet is allowed without reset_statuses. All other profile changes are rejected."],recovery_guidance:"Remove the execution_profile field from this save_plan call to preserve the locked profile, or use reset_statuses: true to start fresh (this clears the lock). Never modify execution_profile directly in plan.json."}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_SPEC_GATE!=="1"){let spec=readEffectiveSpecSync(targetWorkspace);if(!spec&&effectivePlanningProfile==="strict")return{success:!1,message:"SPEC_REQUIRED: an effective spec (native .swarm/spec.md, OpenSpec openspec/specs or openspec/changes, or Spec-Kit .specify/) must exist before saving a plan.",errors:["No effective spec found — .swarm/spec.md is absent and no OpenSpec/Spec-Kit projection succeeded."],recovery_guidance:"Obtain explicit user consent, then run /swarm sdd project (agent-invocable) to materialize an effective spec from SDD sources. If .swarm/spec.md already exists, pass --overwrite after consent. Alternatively, run /swarm specify to author a native spec. Never write .swarm/plan.json or .swarm/plan.md directly."};if(spec){specMtime=spec.mtime??void 0,specHash=spec.hash,specContent=spec.content;try{let snapshotPath=path322.join(targetWorkspace,".swarm","spec-snapshot.md");await fs186.promises.writeFile(snapshotPath,spec.content,"utf-8")}catch{}}}if(!reconcileLedgerProjection&&process.env.SWARM_SKIP_GATE_SELECTION!=="1"){let profileLookup;try{profileLookup=getProfileLookupForIdentity(targetWorkspace,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not verify the durable QA gate selection.",errors:[error93 instanceof Error?`QA gate profile store read failed: ${error93.message}`:"QA gate profile store read failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry get_qa_gate_profile and save_plan with the same swarm_id and title."}}if(profileLookup.kind==="missing")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not create the default balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile bootstrap failed: ${error93.message}`:"QA gate profile bootstrap failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",errors:["No QA gate profile found for the exact plan identity"],recovery_guidance:`Present the PLAN gate dialogue, then call set_qa_gates with swarm_id=${JSON.stringify(args2.swarm_id)} and plan_title=${JSON.stringify(args2.title)} before retrying save_plan with the identical identity.`};else if(profileLookup.kind==="unbound_legacy")if(effectivePlanningProfile==="balanced")try{getOrCreateProfileForIdentity(dir,{swarm:args2.swarm_id,title:args2.title})}catch(error93){return{success:!1,message:"QA_GATE_PROFILE_UNAVAILABLE: save_plan could not exact-bind the balanced QA profile.",errors:[error93 instanceof Error?`QA gate profile exact-bind failed: ${error93.message}`:"QA gate profile exact-bind failed"],recovery_guidance:"Repair access to .swarm/swarm.db, then retry save_plan with the same swarm_id and title."}}else return{success:!1,message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",errors:["QA gate profile exists for the readable plan id, but no exact swarm_id/plan_title binding has been adopted yet."],recovery_guidance:formatLegacyQaBindingRecovery({swarm:args2.swarm_id,title:args2.title},"retry save_plan with the identical identity")}}let requirementCoverage=evaluateRequirementCoverage(specContent,args2);if(!reconcileLedgerProjection&&requirementCoverage?.status==="failed"&&args2.confirm_requirement_coverage_gaps!==!0)return{success:!1,message:"REQUIREMENT_COVERAGE_GAPS: save_plan rejected because required FR-### MUST/SHALL requirements are not mapped to any task.",errors:requirementCoverage.blocking_missing.map((requirement)=>`${requirement.id} (${requirement.obligation}): ${requirement.text}`),recovery_guidance:"Add each required FR-### id to a task description or acceptance criterion, or retry with confirm_requirement_coverage_gaps: true only after surfacing the gaps to the user.",requirement_coverage:requirementCoverage};{let existing=existingPlan;if(existing){if(args2.confirm_identity_change!==!0){if(!(existing.swarm===args2.swarm_id&&existing.title===args2.title)){let existingId=derivePlanId(existing),incomingId=derivePlanId({swarm:args2.swarm_id,title:args2.title});return{success:!1,message:"PLAN_IDENTITY_MISMATCH: The incoming plan identity does not match the existing plan. To overwrite with a new identity, set confirm_identity_change: true.",errors:[`Existing plan identity: ${existingId} (swarm: "${existing.swarm}", title: "${existing.title}")`,`Incoming plan identity: ${incomingId} (swarm: "${args2.swarm_id}", title: "${args2.title}")`],recovery_guidance:"Verify the title and swarm_id match the intended plan. If the identity change is intentional, retry with confirm_identity_change: true. Never write .swarm/plan.json or .swarm/plan.md directly."}}}}}let resolvedProfile=preservedExecutionProfile;if(args2.execution_profile!==void 0){let merged={...preservedExecutionProfile??(args2.execution_profile.parallelization_enabled===void 0?{parallelization_enabled:!0}:{}),...args2.execution_profile},parsed=ExecutionProfileSchema.safeParse(merged);if(!parsed.success)return{success:!1,message:"Invalid execution_profile: schema validation failed",errors:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`),recovery_guidance:'Check execution_profile fields: parallelization_enabled (boolean), max_concurrent_tasks (integer 1-64), council_parallel (boolean), locked (boolean), auto_proceed (boolean), commit_after_each_completed_task (boolean), planning_profile ("balanced" | "strict").'};resolvedProfile=materializeResolvedExecutionProfile(parsed.data,persistedPlanningProfile)}if(resolvedProfile===void 0)resolvedProfile={...ExecutionProfileSchema.parse({}),parallelization_enabled:!0,...persistedPlanningProfile!==void 0?{planning_profile:persistedPlanningProfile}:{}};else if(resolvedProfile.planning_profile===void 0&&persistedPlanningProfile!==void 0)resolvedProfile={...resolvedProfile,planning_profile:persistedPlanningProfile};let incomingTaskIds=new Set;for(let phase of args2.phases)for(let task2 of phase.tasks)incomingTaskIds.add(task2.id);let missingTaskIds=[];for(let id of priorTaskIds)if(!incomingTaskIds.has(id))missingTaskIds.push(id);let rawRemovedIds=args2.removed_task_ids??[];if(rawRemovedIds.length>0){let seen=new Set;for(let id of rawRemovedIds){if(seen.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains duplicate entries",errors:[`Duplicate id in removed_task_ids: "${id}"`],recovery_guidance:"Deduplicate removed_task_ids and retry save_plan."};seen.add(id)}for(let id of rawRemovedIds)if(incomingTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains a task that also appears in args.phases",errors:[`Task "${id}" appears in both removed_task_ids and args.phases — these are contradictory`],recovery_guidance:"A task cannot be both kept and removed in the same save_plan call. Either drop it from args.phases or remove it from removed_task_ids."};for(let id of rawRemovedIds)if(!priorTaskIds.has(id))return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removed_task_ids contains an id that was not in the prior plan",errors:[`Task "${id}" is in removed_task_ids but not present in the prior plan`],recovery_guidance:"Re-read the prior plan and update removed_task_ids to only list tasks that actually existed."}}let resolvedRemovedIds=[...rawRemovedIds],resolvedRemovalReason=args2.removal_reason;if(args2.reset_statuses===!0&&missingTaskIds.length>0){if(args2.confirm_destructive_reset!==!0)return{success:!1,message:"PLAN_DESTRUCTIVE_RESET_NOT_CONFIRMED: reset_statuses with missing tasks requires confirm_destructive_reset: true",errors:[`reset_statuses: true would drop ${missingTaskIds.length} task(s) from the prior plan: ${missingTaskIds.join(", ")}`],recovery_guidance:"Surface the list of dropped tasks to the user and confirm intent before retrying. Pass confirm_destructive_reset: true (with reset_statuses: true) to acknowledge the destructive reset, or list removed_task_ids explicitly with a removal_reason."};if(rawRemovedIds.length===0)resolvedRemovedIds=[...missingTaskIds],resolvedRemovalReason="destructive reset acknowledged"}if(resolvedRemovedIds.length>0){if((resolvedRemovalReason??"").trim().length===0)return{success:!1,message:"PLAN_TASK_REMOVAL_INVALID: removal_reason is required when removed_task_ids is non-empty",errors:["removal_reason must be a non-empty, non-whitespace string"],recovery_guidance:"Provide a removal_reason describing why these tasks are being dropped."}}if(missingTaskIds.length>0){let ackSet=new Set(resolvedRemovedIds),unacked=missingTaskIds.filter((id)=>!ackSet.has(id));if(unacked.length>0)return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[`The following prior tasks are missing from the new save and were not listed in removed_task_ids: ${unacked.join(", ")}`],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(unacked)} and a non-empty removal_reason. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation.`}}let resolvedFilesByTask=new Map;for(let phase of args2.phases)for(let task2 of phase.tasks){if(task2.files_touched===void 0){resolvedFilesByTask.set(task2.id,existingFilesMap.get(task2.id)??[]);continue}if(task2.files_touched.length===0){resolvedFilesByTask.set(task2.id,[]);continue}let normalized=normalizeScopeFiles(task2.files_touched);if(!normalized)return{success:!1,message:"PLAN_TASK_SCOPE_INVALID: files_touched must contain valid project-relative paths",errors:[`Task "${task2.id}" has an invalid files_touched list. Absolute paths, traversal, empty entries, and control characters are not allowed.`],recovery_guidance:"Retry save_plan with normalized project-relative paths, omit files_touched to preserve the prior task scope, or pass [] to clear it explicitly."};resolvedFilesByTask.set(task2.id,normalized)}let plan={schema_version:"1.0.0",title:args2.title,swarm:args2.swarm_id,migration_status:reconcileLedgerProjection?existingPlan?.migration_status:"native",current_phase:reconcileLedgerProjection?existingPlan?.current_phase:args2.phases[0]?.id,specMtime,specHash,...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},phases:args2.phases.map((phase)=>{let existingPhase=reconcileLedgerProjection?existingPlan?.phases.find((candidate2)=>candidate2.id===phase.id):void 0;return{id:phase.id,name:phase.name,status:"pending",type:existingPhase?.type,required_agents:existingPhase?.required_agents?[...existingPhase.required_agents]:void 0,tasks:phase.tasks.map((task2)=>{let existingTask=existingPhase?.tasks.find((candidate2)=>candidate2.id===task2.id);return{id:task2.id,phase:phase.id,status:existingStatusMap.get(task2.id)??"pending",size:task2.size??existingTask?.size??"small",description:task2.description,depends:task2.depends??existingTask?.depends??[],acceptance:task2.acceptance??existingTask?.acceptance,files_touched:resolvedFilesByTask.get(task2.id)??[],evidence_path:existingTask?.evidence_path,blocked_reason:existingTask?.blocked_reason,fr_refs:task2.fr_refs??existingTask?.fr_refs}})}})},tasksCount=plan.phases.reduce((acc,phase)=>acc+phase.tasks.length,0),lockTaskId=`save-plan-${Date.now()}`,planFilePath="plan.json";try{let lockResult=await tryAcquireLock(dir,planFilePath,"architect",lockTaskId);if(!lockResult.acquired)return{success:!1,message:`Plan write blocked: file is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry save_plan. The lock will expire automatically if the holding agent fails."};try{if(reconcileLedgerProjection){let lockedRuntimePlan=await loadPlan(dir).catch(()=>null);if(lockedRuntimePlan?._ledgerReplayStale!==!0)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_NOT_STALE: reconcile_ledger_projection is only allowed when loadPlan reports a stale projection.",errors:[lockedRuntimePlan?"The current plan projection is not marked _ledgerReplayStale.":"The current plan could not be loaded for stale-projection reconciliation."],recovery_guidance:"Use reconcile_ledger_projection only to reconverge a workspace whose plan.json still hash-mismatches the ledger after replay failure."};let lockedTailCapture=await readLedgerTailCapture(dir).catch(()=>null);if(reconcileLedgerTailCapture===null||lockedTailCapture===null||reconcileLedgerTailCapture.seq!==lockedTailCapture.seq||reconcileLedgerTailCapture.plan_hash_after!==lockedTailCapture.plan_hash_after)return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_STALE: the ledger tail changed before save_plan acquired the lock.",errors:["Re-read the stale plan and retry reconcile_ledger_projection against the latest ledger tail."],recovery_guidance:"Retry reconcile_ledger_projection only when the incoming plan still matches the current stale projection exactly."};let comparableIncomingPlan=PlanSchema.parse(JSON.parse(JSON.stringify(plan)));derivePhaseStatusesForComparison(comparableIncomingPlan);let comparableLoadedPlan=PlanSchema.parse(lockedRuntimePlan);if(JSON.stringify(normalizePlanForReconcileComparison(comparableIncomingPlan))!==JSON.stringify(normalizePlanForReconcileComparison(comparableLoadedPlan)))return{success:!1,message:"RECONCILE_LEDGER_PROJECTION_MISMATCH: reconcile_ledger_projection may not change plan semantics.",errors:["Incoming save_plan content does not exactly match the loaded stale projection (identity, task graph, statuses, or execution_profile changed)."],recovery_guidance:"Remove semantic edits and retry reconcile_ledger_projection with the exact stale plan content, or retry save_plan without reconcile_ledger_projection for a normal plan revision."}}await savePlan(dir,plan,{preserveCompletedStatuses:!args2.reset_statuses,planLockAlreadyHeld:!0,...reconcileLedgerProjection&&reconcileLedgerTailCapture?{staleProjectionReconcile:{expectedSeq:reconcileLedgerTailCapture.seq,expectedLedgerHash:reconcileLedgerTailCapture.plan_hash_after}}:{},...resolvedRemovedIds.length>0?{acknowledged_removals:{ids:resolvedRemovedIds,reason:(resolvedRemovalReason??"").trim(),source:"save_plan_tool"}}:{}});let savedPlan=await loadPlanJsonOnly(dir);if(savedPlan)await takeSnapshotWithRetry(dir,savedPlan);if(resolvedProfile!==void 0&&savedPlan){let planId=derivePlanId(plan),planHashAfter=computePlanLedgerHash(savedPlan);if(JSON.stringify(resolvedProfile)!==JSON.stringify(preservedExecutionProfile))await appendLedgerEvent(dir,{event_type:"execution_profile_set",source:"save_plan",plan_id:planId,payload:{execution_profile:resolvedProfile}},{planHashAfter}).catch(()=>{});let wasAlreadyLocked=preservedExecutionProfile?.locked===!0;if(resolvedProfile.locked&&!wasAlreadyLocked)await appendLedgerEvent(dir,{event_type:"execution_profile_locked",source:"save_plan",plan_id:planId},{planHashAfter}).catch(()=>{})}await writeCheckpoint(dir).catch(()=>{});try{let markerPath=path322.join(dir,".swarm",".plan-write-marker"),marker=JSON.stringify({source:"save_plan",timestamp:new Date().toISOString(),phases_count:plan.phases.length,tasks_count:tasksCount});await fs186.promises.writeFile(markerPath,marker,"utf8")}catch{}let warnings=[];if(requirementCoverage?.status==="override"){let missingIds=requirementCoverage.blocking_missing.map((requirement)=>requirement.id).join(", ");warnings.push(`Requirement coverage override used. Missing required FR mappings: ${missingIds}`)}return{success:!0,message:"Plan saved successfully",plan_path:path322.join(dir,".swarm","plan.json"),phases_count:plan.phases.length,tasks_count:tasksCount,...requirementCoverage?{requirement_coverage:requirementCoverage}:{},...resolvedProfile!==void 0?{execution_profile:resolvedProfile}:{},...warnings.length>0?{warnings}:{}}}finally{if(lockResult.acquired&&lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}catch(error93){if(error93 instanceof PlanTaskRemovalNotAcknowledgedError){let ids=error93.missingTasks.map((t)=>t.id);return{success:!1,message:"PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED: this save would silently drop tasks from the prior plan",errors:[error93.message],recovery_guidance:`Re-read the current plan, then retry save_plan with removed_task_ids: ${JSON.stringify(ids)} and a non-empty removal_reason.`}}return{success:!1,message:"Failed to save plan: retry with save_plan after resolving the error above",errors:[error93 instanceof Error?error93.message:String(error93)],recovery_guidance:"Use save_plan with corrected inputs to create or restructure plans. Never write .swarm/plan.json or .swarm/plan.md directly."}}}var save_plan=createSwarmTool({description:"Save or revise a structured implementation plan to .swarm/plan.json and .swarm/plan.md. "+"Use this tool for all structural plan changes on an existing plan (adding/removing tasks, updating descriptions, dependencies, or phase names) — existing task statuses are preserved by default (set reset_statuses: true to start fresh). "+"Task descriptions and phase names MUST contain real content from the spec — "+"bracket placeholders like [task] or [Project] will be rejected.",args:{title:exports_external.string().min(1).describe("Plan title — the REAL project name from the spec. NOT a placeholder like [Project]."),swarm_id:exports_external.string().min(1).describe('Swarm identifier (e.g. "mega")'),phases:exports_external.array(exports_external.object({id:exports_external.number().int().min(1).describe("Phase number — a positive integer starting at 1. Use 1, 2, 3, etc."),name:exports_external.string().min(1).describe("Descriptive phase name derived from the spec"),tasks:exports_external.array(exports_external.object({id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M format, e.g. "1.1"').describe('Task ID in N.M format, e.g. "1.1", "2.3"'),description:exports_external.string().min(1).describe("Specific task description from the spec. NOT a placeholder like [task]."),size:exports_external.enum(["small","medium","large"]).optional().describe("Task size estimate (default: small)"),depends:exports_external.array(exports_external.string()).optional().describe('Task IDs this task depends on, e.g. ["1.1", "1.2"]'),acceptance:exports_external.string().optional().describe("Acceptance criteria for this task"),files_touched:exports_external.array(exports_external.string()).max(1e4).optional().describe("Exact project-relative files or directories this task may modify. Omit on revision to preserve the prior scope; pass [] to clear it explicitly."),fr_refs:exports_external.array(exports_external.string()).optional().describe('Spec FR-###/SC-### IDs this task maps to, e.g. ["FR-001", "SC-002"]')})).min(1).describe("Tasks in this phase")})).min(1).describe("Implementation phases"),working_directory:exports_external.string().optional().describe("Working directory (explicit path, required - no fallback)"),reset_statuses:exports_external.boolean().optional().describe("When true, reset ALL task statuses to pending regardless of prior completion state. Use only when deliberately re-planning a phase from scratch. Default false (preserves existing task statuses across plan revisions)."),removed_task_ids:exports_external.array(exports_external.string()).optional().describe("Task IDs that are present in the prior plan but intentionally being removed by this save. Every task missing from `phases` MUST be enumerated here, otherwise save_plan rejects with PLAN_TASK_REMOVAL_NOT_ACKNOWLEDGED. Tasks not yet finished (status pending/in_progress/blocked) MUST NOT be removed without explicit user confirmation."),removal_reason:exports_external.string().optional().describe("Required when removed_task_ids is non-empty. Human-readable reason recorded on each task_removed ledger event."),confirm_destructive_reset:exports_external.boolean().optional().describe("Required when reset_statuses is true AND at least one task is missing from the new plan. Set true to acknowledge that the destructive reset drops unfinished work. When set together with reset_statuses, save_plan auto-populates removed_task_ids from the missing set."),confirm_identity_change:exports_external.boolean().optional().describe("When true, allows overwriting an existing plan that has a different identity (swarm_id + title). Without this flag, save_plan rejects with PLAN_IDENTITY_MISMATCH if the identity differs."),confirm_requirement_coverage_gaps:exports_external.boolean().optional().describe("When true, allows saving a plan even when required FR-### MUST/SHALL requirements from the effective spec are not explicitly mapped in task descriptions or acceptance criteria. Use only after surfacing the structured requirement_coverage gaps to the user."),execution_profile:exports_external.object({parallelization_enabled:exports_external.boolean().optional().describe("When true, enables parallel task dispatch for this plan. Default false (serial)."),max_concurrent_tasks:exports_external.number().int().min(1).max(64).optional().describe("Maximum tasks that may run concurrently when parallelization is enabled. Default 10."),council_parallel:exports_external.boolean().optional().describe("When true, council review phases may run in parallel. Default true."),locked:exports_external.boolean().optional().describe("When true, locks the profile — future save_plan calls that include "+"execution_profile will be rejected (fail-closed). Unlock by resetting the plan (reset_statuses: true)."),auto_proceed:exports_external.boolean().optional().describe("When true, the architect advances to the next phase automatically without asking for confirmation. Default false."),commit_after_each_completed_task:exports_external.boolean().optional().describe("When true, execution creates a checkpoint commit after each successfully completed task. Default false."),planning_profile:exports_external.enum(["balanced","strict"]).optional().describe("Planning-policy profile. balanced auto-seeds durable defaults and minimizes ceremony; strict requires the full QA questionnaire and an effective spec.")}).optional().describe("Architect-facing concurrency controls. Once locked, cannot be changed without resetting. Omit to preserve the existing profile."),reconcile_ledger_projection:exports_external.boolean().optional().describe("Narrow stale-ledger recovery mode. When true, save_plan only permits an unchanged semantic re-save that reconverges a _ledgerReplayStale plan.json with the authoritative ledger.")},execute:async(args2,_directory)=>{return JSON.stringify(await executeSavePlan(args2,_directory),null,2)}});init_zod();init_manager2();import*as fs187 from"node:fs";import*as path323 from"node:path";init_utils();init_logger();function parsePubspecLock(content){let components=[];if(!content.match(/^packages:\s*$/m))return components;let lines=content.split(`
|
|
7123
7123
|
`),inPackages=!1,currentPackage="",currentVersion="";for(let i=0;i<lines.length;i++){let line=lines[i],trimmed=line.replace(/^ {2}/,"");if(trimmed==="packages:"||trimmed.startsWith("packages:")){inPackages=!0;continue}if(!inPackages)continue;let packageMatch=line.match(/^ {2}([a-zA-Z0-9_-]+):\s*$/);if(packageMatch){if(currentPackage&¤tVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});currentPackage=packageMatch[1],currentVersion="";continue}if(currentPackage&&line.includes("version:")){let versionMatch=line.match(/version:\s*"([^"]+)"/);if(versionMatch)currentVersion=versionMatch[1]}}if(currentPackage&¤tVersion)components.push({name:currentPackage,version:currentVersion,type:"library",purl:generatePurl("pub",currentPackage,currentVersion)});return components}function parsePubspecYaml(content){let components=[],lines=content.split(`
|
|
7124
7124
|
`),inDependencies=!1,inDevDependencies=!1;for(let line of lines){let trimmed=line.trim();if(trimmed==="dependencies:"){inDependencies=!0,inDevDependencies=!1;continue}if(trimmed==="dev_dependencies:"){inDependencies=!1,inDevDependencies=!0;continue}if(trimmed==="dependencies_overrides:"||trimmed==="dev_dependencies_overrides:"||trimmed.startsWith("environment:")){inDependencies=!1,inDevDependencies=!1;continue}if(!inDependencies&&!inDevDependencies)continue;if(!trimmed||trimmed.startsWith("#")||trimmed.includes("sdk:"))continue;let match=trimmed.match(/^([a-zA-Z0-9_-]+):\s*(.+)?$/);if(match){let name=match[1],value=match[2]||"";if(name==="flutter"||name==="environment")continue;let version5="unknown",caretMatch=value.match(/\^?([\d.]+)/);if(caretMatch)version5=caretMatch[1];let hostedMatch=value.match(/version:\s*"?\^?([\d.]+)/);if(hostedMatch)version5=hostedMatch[1];if(name&&version5!=="unknown")components.push({name,version:version5,type:"library",purl:generatePurl("pub",name,version5)})}}return components}var dartDetectors=[{name:"Dart pubspec.lock",patterns:["pubspec.lock"],detect:(_filePath,content)=>{return parsePubspecLock(content)}},{name:"Dart pubspec.yaml",patterns:["pubspec.yaml"],detect:(_filePath,content)=>{return parsePubspecYaml(content)}}];function parsePackagesLockJson(content){let components=[];try{let lock=JSON.parse(content),targets=lock.targets||lock.dependencies||{};for(let[_target,targetDeps]of Object.entries(targets)){if(!targetDeps||typeof targetDeps!=="object")continue;for(let[pkgSpec,pkgData]of Object.entries(targetDeps)){if(!pkgSpec.includes("/"))continue;let[name,version5]=pkgSpec.split("/"),pkg=pkgData;if(name&&version5)components.push({name,version:version5,type:"library",purl:generatePurl("nuget",name,version5),license:pkg.license})}}}catch{}return components}function parsePaketLock(content){let components=[],lines=content.split(`
|
|
7125
7125
|
`),inNuGetSection=!1;for(let line of lines){let trimmed=line.trim();if(trimmed==="NUGET"||trimmed.startsWith("NUGET")){inNuGetSection=!0;continue}if(trimmed==="GITHUB"||trimmed.startsWith("GITHUB")){inNuGetSection=!1;continue}if(!inNuGetSection)continue;if(!trimmed||trimmed.startsWith("remote:")||trimmed.startsWith("->"))continue;let match=trimmed.match(/^([a-zA-Z0-9_.-]+)\s+\(([^)]+)\)/);if(match){let name=match[1],version5=match[2];if(name&&version5)components.push({name,version:version5,type:"library",purl:generatePurl("nuget",name,version5)})}}return components}var dotnetDetectors=[{name:".NET packages.lock.json",patterns:["packages.lock.json"],detect:(_filePath,content)=>{return parsePackagesLockJson(content)}},{name:".NET paket.lock",patterns:["paket.lock"],detect:(_filePath,content)=>{return parsePaketLock(content)}}];function parseGoMod(content){let components=[],lines=content.split(`
|
|
@@ -7171,7 +7171,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
|
|
|
7171
7171
|
`).replace(/\n{3,}/g,`
|
|
7172
7172
|
|
|
7173
7173
|
`).trim()}function makeAbortError(){try{return new DOMException("The operation was aborted","AbortError")}catch{let err2=Error("The operation was aborted");return err2.name="AbortError",err2}}function performHttpRequest(args2){let{url:url3,pinnedAddress,signal:signal2,headers}=args2,isHttps=url3.protocol==="https:",port=url3.port?Number(url3.port):isHttps?443:80,hostNoBrackets=url3.hostname.replace(/^\[|\]$/g,""),useSni=isHttps&&isIP(hostNoBrackets)===0,options={host:pinnedAddress,port,path:`${url3.pathname}${url3.search}`,method:"GET",headers:{Host:url3.host,...headers}};if(useSni)options.servername=url3.hostname;return new Promise((resolve149,reject2)=>{let req,onResponse=(res)=>{let normHeaders={};for(let[key2,value]of Object.entries(res.headers))normHeaders[key2]=Array.isArray(value)?value[0]:value;res.on("error",()=>{}),resolve149({status:res.statusCode??0,headers:normHeaders,body:res,cancel:()=>req.destroy()})};req=isHttps?https.request(options,onResponse):http.request(options,onResponse);let onAbort=()=>req.destroy(makeAbortError());if(signal2.aborted)req.destroy(makeAbortError());else signal2.addEventListener("abort",onAbort,{once:!0});req.on("error",reject2),req.end()})}async function boundedFetch(start,maxBytes,timeoutMs,deps){let current=start,controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);try{for(let hop=0;hop<=MAX_REDIRECTS;hop++){let raw;try{raw=await deps.httpRequest({url:current.url,pinnedAddress:current.address,signal:controller.signal,headers:{Accept:"text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.5"}})}catch(err2){if(controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms for ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}if(raw.status>=300&&raw.status<400){let location=raw.headers.location;if(raw.cancel?.(),!location)return{ok:!1,reason:"bad_redirect",message:`Redirect ${raw.status} with no Location header.`};let next;try{next=new URL(location,current.url)}catch{return{ok:!1,reason:"bad_redirect",message:`Invalid redirect target: ${location}`}}let revalidated=await validateFetchUrl(next.toString(),deps.dnsLookup);if(!revalidated.ok)return revalidated;if(hop===MAX_REDIRECTS)return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`};current={url:revalidated.url,address:revalidated.address};continue}if(raw.status<200||raw.status>=300)return raw.cancel?.(),{ok:!1,reason:"http_error",message:`HTTP ${raw.status} for ${current.url.toString()}`};let contentType=raw.headers["content-type"]??null;if(!isAllowedContentType(contentType))return raw.cancel?.(),{ok:!1,reason:"unsupported_content_type",message:`Refusing to read non-text content type "${contentType}".`};let activeBody=raw.body;if(raw.body!==null&&raw.body instanceof Readable){let encoding=(raw.headers["content-encoding"]??"").toLowerCase(),decoder=null;if(encoding==="gzip"||encoding==="x-gzip")decoder=raw.body.pipe(zlib.createGunzip());else if(encoding==="deflate")decoder=raw.body.pipe(zlib.createInflate());else if(encoding==="br")decoder=raw.body.pipe(zlib.createBrotliDecompress());if(decoder)decoder.on("error",()=>{}),activeBody=decoder}let body;try{body=await readBounded(activeBody,maxBytes)}catch(err2){if(raw.cancel?.(),controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms while reading the body of ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}return raw.cancel?.(),{ok:!0,outcome:{status:raw.status,finalUrl:current.url.toString(),contentType,bytes:body.bytes,truncated:body.truncated}}}return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`}}finally{clearTimeout(timer)}}async function readBounded(body,maxBytes){if(!body)return{bytes:new Uint8Array(0),truncated:!1};let chunks=[],received=0,truncated=!1;for await(let value of body){if(!value||value.byteLength===0)continue;if(chunks.push(value),received+=value.byteLength,received>maxBytes){truncated=!0;break}}let merged=new Uint8Array(Math.min(received,maxBytes)),offset=0;for(let chunk of chunks){if(offset>=merged.length)break;let slice=chunk.subarray(0,merged.length-offset);merged.set(slice,offset),offset+=slice.byteLength}return{bytes:merged,truncated}}var web_fetch=createSwarmTool({description:"Fetch the readable text of a single http(s) URL for architect-driven deep research (MODE: DEEP_RESEARCH). Returns decoded page text (HTML stripped to plain text), the document title, the final URL after redirects, and an evidence reference stored alongside web_search results. Use it to read primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled; no search API key required. Blocks private/loopback/link-local/metadata addresses (re-validated across redirects), enforces a timeout, and caps the response body size.",args:{url:exports_external.string().min(1).max(2048).describe("Absolute http(s) URL to fetch (1–2048 chars)."),max_bytes:exports_external.number().int().min(1024).max(MAX_BYTES_HARD_CAP).optional().describe(`Max decoded response bytes to read (1024..${MAX_BYTES_HARD_CAP}, default ${DEFAULT_MAX_BYTES2}).`),timeout_ms:exports_external.number().int().min(1000).max(MAX_TIMEOUT_MS5).optional().describe(`Request timeout in ms (1000..${MAX_TIMEOUT_MS5}, default ${DEFAULT_TIMEOUT_MS6}).`),working_directory:exports_external.string().optional().describe("Project root for config resolution and evidence storage. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema6.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=_internals263.loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_fetch is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let validated=await validateFetchUrl(parsed.data.url,_internals263.dnsLookup);if(!validated.ok){let fail={success:!1,reason:validated.reason,message:validated.message};return JSON.stringify(fail,null,2)}let maxBytes=parsed.data.max_bytes??DEFAULT_MAX_BYTES2,timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS6,result=await boundedFetch({url:validated.url,address:validated.address},maxBytes,timeoutMs,_internals263);if(!result.ok){let fail={success:!1,reason:result.reason,message:result.message};return JSON.stringify(fail,null,2)}let{outcome}=result,raw=new TextDecoder("utf-8",{fatal:!1}).decode(outcome.bytes),isHtml=(outcome.contentType??"").toLowerCase().includes("html")||/<html|<!doctype html/i.test(raw),title=isHtml?extractTitle(raw):void 0,bodyText=isHtml?htmlToText(raw):raw.replace(/\s*\n\s*/g,`
|
|
7174
|
-
`).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals263.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals263={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now2=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now2.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals264.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals264={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();import*as path335 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path335.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs196 from"node:fs";import path336 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals265.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals265.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path336.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path336.dirname(validatedPath);try{await fs196.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path336.join(evidenceDir,`.${filename}.tmp`);return await fs196.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs196.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals265={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();init_council_review_identity();import fs197 from"node:fs";import path337 from"node:path";init_types();init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=COUNCIL_MEMBER_ROLES,VerdictSchema3=exports_external.object({agent:exports_external.string().min(1).max(64),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function resolveFinalCouncilVerdicts(verdicts){let resolved=[],distinctRoles=[],unknownAgents=[],duplicateAgents=[];for(let verdict of verdicts){let role=resolveCouncilMemberRole(verdict.agent);if(!role){if(!unknownAgents.includes(verdict.agent))unknownAgents.push(verdict.agent);continue}if(distinctRoles.includes(role)){if(!duplicateAgents.includes(verdict.agent))duplicateAgents.push(verdict.agent);continue}distinctRoles.push(role),resolved.push({...verdict,agent:role})}return{resolved,distinctRoles,unknownAgents,duplicateAgents}}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,reviewHash=plan?computeCouncilReviewHash(plan):null,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan,config:config3.council}),completionPolicy=resolveFinalCompletionPolicy(config3.council),{resolved,distinctRoles,unknownAgents,duplicateAgents}=resolveFinalCouncilVerdicts(input.verdicts),membersVoted=distinctRoles,membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!distinctRoles.includes(member)),requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:FINAL_COUNCIL_MEMBERS.length;return runCouncilAttempt({directory,scope:{kind:"final",identityDigest:identity.identityDigest},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,escalationConfigured:config3.council?.escalateOnMaxRounds!==void 0,request:input,verdictCount:input.verdicts.length,members:[...new Set(input.verdicts.map((v)=>v.agent))].slice(0,5),probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<requiredMembers)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${requiredMembers} required distinct canonical members provided verdicts (policy: ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}). Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}].`+(unknownAgents.length>0?` Unknown identities (never counted): [${unknownAgents.join(", ")}].`:"")+(duplicateAgents.length>0?` Duplicate identities (collapsed): [${duplicateAgents.join(", ")}].`:"")+" Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.",membersVoted,membersAbsent,quorumRequired:requiredMembers,completionPolicy,...unknownAgents.length>0?{unknownAgents}:{},...duplicateAgents.length>0?{duplicateAgents}:{}},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),resolved,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,...councilIdentityEvidenceFields(identity),final_completion_policy:completionPolicy,freshness_max_age_hours:config3.council?.freshnessMaxAgeHours??24,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals266.validateSwarmPath(directory,path337.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path337.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,completionPolicy,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path337.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computeCouncilReviewHash(currentPlan)!==reviewHash)throw Error("final council plan changed before evidence publication");await fs197.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path337.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs197.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs197.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs197.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json. Quorum follows council.finalCompletionPolicy: default requires all five canonical roles with zero absentees; an explicit quorum policy accepts a bounded minimum of distinct canonical members. Member names may be exact canonical roles or multi-swarm prefixed names (e.g. local_critic); unknown and duplicate identities never count.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer (canonical or multi-swarm prefixed names).")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path337.join("evidence","final-council.json")),parsed=JSON.parse(fs197.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals266={validateSwarmPath};init_zod();import fs198 from"node:fs";import path338 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals267.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path338.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path338.dirname(validatedPath);try{await fs198.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path338.join(evidenceDir,`.${filename}.tmp`);return await fs198.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs198.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals267={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs199 from"node:fs";import path339 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals268.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path339.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path339.dirname(validatedPath);try{await fs199.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path339.join(evidenceDir,`.${filename}.tmp`);return await fs199.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs199.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals268={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_review_contract();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID40}from"node:crypto";import*as fs200 from"node:fs";import*as path340 from"node:path";var PersistedFindingSchema=PrReviewFindingSchema.extend({boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),recorded_at:exports_external.string().datetime()}).strict(),PersistedHandoffSchema=PrReviewHandoffSchema.extend({schema_version:exports_external.literal(1),run_id:PrReviewRunIdSchema,pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime()}).strict();function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{return(await readBoundedUtf8File(filePath,PR_REVIEW_FINDINGS_MAX_BYTES,"findings artifact")).split(/\r?\n/).filter(Boolean).map((line,index)=>{let decoded;try{decoded=JSON.parse(line)}catch(error93){throw Error(`line ${index+1} is not JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(decoded!==null&&typeof decoded==="object"){let record3=decoded;if(record3.risk_impact===void 0)record3.risk_impact="UNKNOWN";if(record3.risk_tags===void 0)record3.risk_tags=[]}let parsed=PersistedFindingSchema.safeParse(decoded);if(!parsed.success)throw Error(`line ${index+1} violates the persisted finding schema: ${formatPrReviewValidationIssues(parsed.error.issues,decoded).join("; ")}`);return parsed.data})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function readBoundedUtf8File(filePath,maxBytes,label){let stat23=await fs200.promises.stat(filePath);if(!stat23.isFile()||stat23.size>maxBytes)throw Error(`${label} is not a bounded regular file (max ${maxBytes} bytes)`);let text=await fs200.promises.readFile(filePath,"utf8"),bytes=Buffer.byteLength(text,"utf8");if(bytes>maxBytes)throw Error(`${label} exceeds ${maxBytes} bytes after read (got ${bytes})`);return text}async function atomicWrite7(filePath,content){await fs200.promises.mkdir(path340.dirname(filePath),{recursive:!0});let tempPath=path340.join(path340.dirname(filePath),`.${path340.basename(filePath)}.${randomUUID40()}.tmp`);try{await fs200.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs200.promises.rename(tempPath,filePath)}finally{await fs200.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function atomicCreate(filePath,content){await fs200.promises.mkdir(path340.dirname(filePath),{recursive:!0});let tempPath=path340.join(path340.dirname(filePath),`.${path340.basename(filePath)}.${randomUUID40()}.tmp`);try{await fs200.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs200.promises.link(tempPath,filePath),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs200.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}var _internals269={atomicWrite:atomicWrite7,atomicCreate,assertBoundary:assertPrReviewArtifactBoundary,readFindings};function operationFailure(operation,relativePath2,expected,error93){return failure3(`operation ${operation} path "${relativePath2}": expected ${expected}, got ${JSON.stringify(error93 instanceof Error?error93.message:String(error93))}`)}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}function canonicalFindingRecords(records){return JSON.stringify(records.map((record3)=>({finding_id:record3.finding_id,status:record3.status,file_line:record3.file_line,evidence:record3.evidence,next_action:record3.next_action,severity:record3.severity,category:record3.category,risk_impact:record3.risk_impact,risk_tags:record3.risk_tags})).sort((left,right)=>left.finding_id.localeCompare(right.finding_id)))}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3(formatPrReviewRuntimeFieldError("session_id","a non-empty active session identifier",context.sessionID));let state;try{state=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return operationFailure("read",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a bounded valid PR workflow state artifact",error93)}if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3(formatPrReviewRuntimeFieldError("workflow.mode",'an active head-bound "PR_REVIEW" workflow',state?{mode:state.mode,pr_head_sha:state.prHeadSha}:null));if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(formatPrReviewRuntimeFieldError("pr_head_sha",`"${state.prHeadSha}"`,parsed.data.pr_head_sha));let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return message.startsWith("BLOCKED: field ")?failure3(message):operationFailure("reserve",`pr-review/${parsed.data.run_id??"<generated-run-id>"}/run-reservation.json`,"a create-only reservation owned by the active workflow",error93)}let relativeFindingsPath=path340.join("pr-review",resolvedRunId,"findings.jsonl"),findingsPath;try{findingsPath=validateSwarmPath(directory,relativeFindingsPath)}catch(error93){return operationFailure("resolve",relativeFindingsPath.split(path340.sep).join("/"),"a contained path below the project .swarm directory",error93)}let existing;try{existing=await readFindings(findingsPath)}catch(error93){return failure3(`operation read path "${relativeFindingsPath.split(path340.sep).join("/")}": expected bounded JSONL matching the persisted findings schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id),existingBoundaryRecords=existing.filter((record3)=>record3.boundary===findingsInput.boundary),hasExistingBoundaryRecords=existingBoundaryRecords.length>0,isExactReplay=hasExistingBoundaryRecords&&canonicalFindingRecords(existingBoundaryRecords)===canonicalFindingRecords(findingsInput.records),boundaryCommitted=state.prReviewArtifactRunId===resolvedRunId&&(state.prReviewArtifactBoundaries??[]).includes(findingsInput.boundary),existingBoundaryIds=new Set(existingBoundaryRecords.map((record3)=>record3.finding_id)),requestedFindingIds=new Set(findingIds),isPostExplorerSupersession=boundaryCommitted&&findingsInput.boundary==="post_explorer"&&Boolean(state.prReviewTriggerEvalPath)&&existingBoundaryIds.size<requestedFindingIds.size&&[...existingBoundaryIds].every((id)=>requestedFindingIds.has(id)),isCommittedReplay=isExactReplay&&boundaryCommitted,partialAdmissionToRollback,rollbackPartialAdmission=async()=>{if(!partialAdmissionToRollback)return;try{return await rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,partialAdmissionToRollback)?void 0:"partial base coverage admission could not be safely rolled back because durable state changed"}catch(error93){return`partial base coverage admission rollback failed: ${error93 instanceof Error?error93.message:String(error93)}`}},withPartialAdmissionRollback=async(result)=>{let rollbackError=await rollbackPartialAdmission();if(!rollbackError)return result;try{let decoded=JSON.parse(result);return typeof decoded.message==="string"?failure3(`${decoded.message}; ${rollbackError}`):result}catch{return result}};if(!isCommittedReplay)try{await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,findingsInput.partial_base_coverage?{skipBaseCoverage:!0}:void 0)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}try{await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records)}catch(error93){return failure3(formatPrReviewRuntimeFieldError("records",`records exactly matching authoritative ${findingsInput.boundary} verdicts and disposition rules`,error93 instanceof Error?error93.message:String(error93)))}if(hasExistingBoundaryRecords&&boundaryCommitted&&!isExactReplay&&!isPostExplorerSupersession)return failure3(formatPrReviewRuntimeFieldError("records",`an exact replay of the already-persisted "${findingsInput.boundary}" boundary`,findingsInput.records));if(!isCommittedReplay)try{if(findingsInput.partial_base_coverage){let hadPartialAdmission=Boolean(state.prReviewPartialBaseCoverage||state.prReviewCoverageDisclosurePath||state.prReviewCoverageDisclosureDigest);if(await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,{skipBaseCoverage:!0}),state=await admitPrReviewPartialBaseCoverage2(directory,sessionID,resolvedRunId,findingsInput.partial_base_coverage.unresolved_dimensions),!hadPartialAdmission&&state.prReviewPartialBaseCoverage&&state.prReviewCoverageDisclosurePath&&state.prReviewCoverageDisclosureDigest)partialAdmissionToRollback={runId:state.prReviewPartialBaseCoverage.runId,boundary:findingsInput.boundary,relativePath:state.prReviewCoverageDisclosurePath,digest:state.prReviewCoverageDisclosureDigest}}if(findingsInput.partial_base_coverage)await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}let recordedAt=new Date().toISOString(),appended=isExactReplay?[]:findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];if(!isExactReplay){let serializedFindings=allRecords.map((record3)=>JSON.stringify(record3)).join(`
|
|
7174
|
+
`).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals263.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals263={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now2=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now2.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals264.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals264={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();import*as path335 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path335.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs196 from"node:fs";import path336 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals265.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals265.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path336.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path336.dirname(validatedPath);try{await fs196.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path336.join(evidenceDir,`.${filename}.tmp`);return await fs196.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs196.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals265={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();init_council_review_identity();import fs197 from"node:fs";import path337 from"node:path";init_types();init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=COUNCIL_MEMBER_ROLES,VerdictSchema3=exports_external.object({agent:exports_external.string().min(1).max(64),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function resolveFinalCouncilVerdicts(verdicts){let resolved=[],distinctRoles=[],unknownAgents=[],duplicateAgents=[];for(let verdict of verdicts){let role=resolveCouncilMemberRole(verdict.agent);if(!role){if(!unknownAgents.includes(verdict.agent))unknownAgents.push(verdict.agent);continue}if(distinctRoles.includes(role)){if(!duplicateAgents.includes(verdict.agent))duplicateAgents.push(verdict.agent);continue}distinctRoles.push(role),resolved.push({...verdict,agent:role})}return{resolved,distinctRoles,unknownAgents,duplicateAgents}}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanLedgerHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,reviewHash=plan?computeCouncilReviewHash(plan):null,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan,config:config3.council}),completionPolicy=resolveFinalCompletionPolicy(config3.council),{resolved,distinctRoles,unknownAgents,duplicateAgents}=resolveFinalCouncilVerdicts(input.verdicts),membersVoted=distinctRoles,membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!distinctRoles.includes(member)),requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:FINAL_COUNCIL_MEMBERS.length;return runCouncilAttempt({directory,scope:{kind:"final",identityDigest:identity.identityDigest},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,escalationConfigured:config3.council?.escalateOnMaxRounds!==void 0,request:input,verdictCount:input.verdicts.length,members:[...new Set(input.verdicts.map((v)=>v.agent))].slice(0,5),probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<requiredMembers)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${requiredMembers} required distinct canonical members provided verdicts (policy: ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}). Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}].`+(unknownAgents.length>0?` Unknown identities (never counted): [${unknownAgents.join(", ")}].`:"")+(duplicateAgents.length>0?` Duplicate identities (collapsed): [${duplicateAgents.join(", ")}].`:"")+" Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.",membersVoted,membersAbsent,quorumRequired:requiredMembers,completionPolicy,...unknownAgents.length>0?{unknownAgents}:{},...duplicateAgents.length>0?{duplicateAgents}:{}},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),resolved,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,...councilIdentityEvidenceFields(identity),final_completion_policy:completionPolicy,freshness_max_age_hours:config3.council?.freshnessMaxAgeHours??24,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals266.validateSwarmPath(directory,path337.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path337.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,completionPolicy,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path337.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computeCouncilReviewHash(currentPlan)!==reviewHash)throw Error("final council plan changed before evidence publication");await fs197.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path337.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs197.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs197.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs197.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json. Quorum follows council.finalCompletionPolicy: default requires all five canonical roles with zero absentees; an explicit quorum policy accepts a bounded minimum of distinct canonical members. Member names may be exact canonical roles or multi-swarm prefixed names (e.g. local_critic); unknown and duplicate identities never count.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer (canonical or multi-swarm prefixed names).")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path337.join("evidence","final-council.json")),parsed=JSON.parse(fs197.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals266={validateSwarmPath};init_zod();import fs198 from"node:fs";import path338 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals267.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path338.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path338.dirname(validatedPath);try{await fs198.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path338.join(evidenceDir,`.${filename}.tmp`);return await fs198.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs198.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals267={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs199 from"node:fs";import path339 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals268.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path339.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path339.dirname(validatedPath);try{await fs199.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path339.join(evidenceDir,`.${filename}.tmp`);return await fs199.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs199.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals268={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_review_contract();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID40}from"node:crypto";import*as fs200 from"node:fs";import*as path340 from"node:path";var PersistedFindingSchema=PrReviewFindingSchema.extend({boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),recorded_at:exports_external.string().datetime()}).strict(),PersistedHandoffSchema=PrReviewHandoffSchema.extend({schema_version:exports_external.literal(1),run_id:PrReviewRunIdSchema,pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime()}).strict();function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{return(await readBoundedUtf8File(filePath,PR_REVIEW_FINDINGS_MAX_BYTES,"findings artifact")).split(/\r?\n/).filter(Boolean).map((line,index)=>{let decoded;try{decoded=JSON.parse(line)}catch(error93){throw Error(`line ${index+1} is not JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(decoded!==null&&typeof decoded==="object"){let record3=decoded;if(record3.risk_impact===void 0)record3.risk_impact="UNKNOWN";if(record3.risk_tags===void 0)record3.risk_tags=[]}let parsed=PersistedFindingSchema.safeParse(decoded);if(!parsed.success)throw Error(`line ${index+1} violates the persisted finding schema: ${formatPrReviewValidationIssues(parsed.error.issues,decoded).join("; ")}`);return parsed.data})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function readBoundedUtf8File(filePath,maxBytes,label){let stat23=await fs200.promises.stat(filePath);if(!stat23.isFile()||stat23.size>maxBytes)throw Error(`${label} is not a bounded regular file (max ${maxBytes} bytes)`);let text=await fs200.promises.readFile(filePath,"utf8"),bytes=Buffer.byteLength(text,"utf8");if(bytes>maxBytes)throw Error(`${label} exceeds ${maxBytes} bytes after read (got ${bytes})`);return text}async function atomicWrite7(filePath,content){await fs200.promises.mkdir(path340.dirname(filePath),{recursive:!0});let tempPath=path340.join(path340.dirname(filePath),`.${path340.basename(filePath)}.${randomUUID40()}.tmp`);try{await fs200.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs200.promises.rename(tempPath,filePath)}finally{await fs200.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function atomicCreate(filePath,content){await fs200.promises.mkdir(path340.dirname(filePath),{recursive:!0});let tempPath=path340.join(path340.dirname(filePath),`.${path340.basename(filePath)}.${randomUUID40()}.tmp`);try{await fs200.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs200.promises.link(tempPath,filePath),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs200.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}var _internals269={atomicWrite:atomicWrite7,atomicCreate,assertBoundary:assertPrReviewArtifactBoundary,readFindings};function operationFailure(operation,relativePath2,expected,error93){return failure3(`operation ${operation} path "${relativePath2}": expected ${expected}, got ${JSON.stringify(error93 instanceof Error?error93.message:String(error93))}`)}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}function canonicalFindingRecords(records){return JSON.stringify(records.map((record3)=>({finding_id:record3.finding_id,status:record3.status,file_line:record3.file_line,evidence:record3.evidence,next_action:record3.next_action,severity:record3.severity,category:record3.category,risk_impact:record3.risk_impact,risk_tags:record3.risk_tags})).sort((left,right)=>left.finding_id.localeCompare(right.finding_id)))}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3(formatPrReviewRuntimeFieldError("session_id","a non-empty active session identifier",context.sessionID));let state;try{state=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return operationFailure("read",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a bounded valid PR workflow state artifact",error93)}if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3(formatPrReviewRuntimeFieldError("workflow.mode",'an active head-bound "PR_REVIEW" workflow',state?{mode:state.mode,pr_head_sha:state.prHeadSha}:null));if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(formatPrReviewRuntimeFieldError("pr_head_sha",`"${state.prHeadSha}"`,parsed.data.pr_head_sha));let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return message.startsWith("BLOCKED: field ")?failure3(message):operationFailure("reserve",`pr-review/${parsed.data.run_id??"<generated-run-id>"}/run-reservation.json`,"a create-only reservation owned by the active workflow",error93)}let relativeFindingsPath=path340.join("pr-review",resolvedRunId,"findings.jsonl"),findingsPath;try{findingsPath=validateSwarmPath(directory,relativeFindingsPath)}catch(error93){return operationFailure("resolve",relativeFindingsPath.split(path340.sep).join("/"),"a contained path below the project .swarm directory",error93)}let existing;try{existing=await readFindings(findingsPath)}catch(error93){return failure3(`operation read path "${relativeFindingsPath.split(path340.sep).join("/")}": expected bounded JSONL matching the persisted findings schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id),existingBoundaryRecords=existing.filter((record3)=>record3.boundary===findingsInput.boundary),hasExistingBoundaryRecords=existingBoundaryRecords.length>0,isExactReplay=hasExistingBoundaryRecords&&canonicalFindingRecords(existingBoundaryRecords)===canonicalFindingRecords(findingsInput.records),boundaryCommitted=state.prReviewArtifactRunId===resolvedRunId&&(state.prReviewArtifactBoundaries??[]).includes(findingsInput.boundary),existingBoundaryIds=new Set(existingBoundaryRecords.map((record3)=>record3.finding_id)),requestedFindingIds=new Set(findingIds),isPostExplorerSupersession=boundaryCommitted&&findingsInput.boundary==="post_explorer"&&Boolean(state.prReviewTriggerEvalPath)&&existingBoundaryIds.size<requestedFindingIds.size&&[...existingBoundaryIds].every((id)=>requestedFindingIds.has(id)),isCommittedReplay=isExactReplay&&boundaryCommitted,partialAdmissionToRollback,rollbackPartialAdmission=async()=>{if(!partialAdmissionToRollback)return;try{return await rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,partialAdmissionToRollback)?void 0:"partial base coverage admission could not be safely rolled back because durable state changed"}catch(error93){return`partial base coverage admission rollback failed: ${error93 instanceof Error?error93.message:String(error93)}`}},withPartialAdmissionRollback=async(result)=>{let rollbackError=await rollbackPartialAdmission();if(!rollbackError)return result;try{let decoded=JSON.parse(result);return typeof decoded.message==="string"?failure3(`${decoded.message}; ${rollbackError}`):result}catch{return result}};if(!isCommittedReplay)try{await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,findingsInput.partial_base_coverage?{skipBaseCoverage:!0}:void 0)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}try{await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records)}catch(error93){return failure3(formatPrReviewRuntimeFieldError("records",`records exactly matching authoritative ${findingsInput.boundary} verdicts and disposition rules`,error93 instanceof Error?error93.message:String(error93)))}if(hasExistingBoundaryRecords&&boundaryCommitted&&!isExactReplay&&!isPostExplorerSupersession)return failure3(formatPrReviewRuntimeFieldError("records",`an exact replay of the already-persisted "${findingsInput.boundary}" boundary`,findingsInput.records));if(!isCommittedReplay)try{if(findingsInput.partial_base_coverage){let hadPartialAdmission=Boolean(state.prReviewPartialBaseCoverage||state.prReviewCoverageDisclosurePath||state.prReviewCoverageDisclosureDigest);if(await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,{skipBaseCoverage:!0}),state=await admitPrReviewPartialBaseCoverage2(directory,sessionID,resolvedRunId,findingsInput.partial_base_coverage.unresolved_dimensions),!hadPartialAdmission&&state.prReviewPartialBaseCoverage&&state.prReviewCoverageDisclosurePath&&state.prReviewCoverageDisclosureDigest)partialAdmissionToRollback={runId:state.prReviewPartialBaseCoverage.runId,boundary:findingsInput.boundary,relativePath:state.prReviewCoverageDisclosurePath,digest:state.prReviewCoverageDisclosureDigest}}if(findingsInput.partial_base_coverage)await _internals269.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}let recordedAt=new Date().toISOString(),appended=isExactReplay?[]:findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];if(!isExactReplay){let serializedFindings=allRecords.map((record3)=>JSON.stringify(record3)).join(`
|
|
7175
7175
|
`)+(allRecords.length>0?`
|
|
7176
7176
|
`:""),serializedBytes=Buffer.byteLength(serializedFindings,"utf8");if(serializedBytes>PR_REVIEW_FINDINGS_MAX_BYTES)return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError("records",`a complete findings artifact at most ${PR_REVIEW_FINDINGS_MAX_BYTES} UTF-8 bytes`,`${serializedBytes} bytes`)));try{await _internals269.atomicWrite(findingsPath,serializedFindings)}catch(error93){return withPartialAdmissionRollback(operationFailure("write",relativeFindingsPath.split(path340.sep).join("/"),"an atomic findings checkpoint write",error93))}}let handoffRequired=[...latestFindings(allRecords).values()].some((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback");if(!isCommittedReplay)try{await markPrReviewArtifactBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,relativeFindingsPath.split(path340.sep).join("/"),findingIds,handoffRequired)}catch(error93){return withPartialAdmissionRollback(operationFailure("update",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,`a durable ${findingsInput.boundary} boundary receipt`,error93))}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeFindingsPath.split(path340.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,replayed:isExactReplay,handoff_required:handoffRequired,...state.prReviewPartialBaseCoverage?{partial_base_coverage:{unresolved_dimensions:normalizePrReviewPartialBaseCoverageRecord(state.prReviewPartialBaseCoverage).unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),path:state.prReviewCoverageDisclosurePath,digest:state.prReviewCoverageDisclosureDigest}}:{}},null,2)}let actionableIds=[...latestFindings(existing).values()].filter((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback").map((record3)=>record3.finding_id).sort(),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`field handoff.finding_ids: expected authoritative actionable set [${actionableIds.join(", ")||"(none)"}], got requested [${requestedIds.join(", ")||"(none)"}]`);let relativeHandoffPath=path340.join("pr-review",resolvedRunId,"feedback-handoff.json"),handoffPath;try{handoffPath=validateSwarmPath(directory,relativeHandoffPath)}catch(error93){return operationFailure("resolve",relativeHandoffPath.split(path340.sep).join("/"),"a contained path below the project .swarm directory",error93)}let handoffRecord={schema_version:1,run_id:resolvedRunId,pr_head_sha:state.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},comparableHandoff=(record3)=>({schema_version:record3.schema_version,run_id:record3.run_id,pr_head_sha:record3.pr_head_sha,pr_url:record3.pr_url,finding_ids:record3.finding_ids,summary:record3.summary,provenance:record3.provenance}),handoffsMatch=(existing2)=>JSON.stringify(comparableHandoff(existing2))===JSON.stringify(comparableHandoff(handoffRecord)),readPersistedHandoff=async()=>{let raw=await readBoundedUtf8File(handoffPath,PR_REVIEW_HANDOFF_MAX_BYTES,"handoff artifact"),decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`invalid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}let validated=PersistedHandoffSchema.safeParse(decoded);if(!validated.success)throw Error(`schema mismatch: ${formatPrReviewValidationIssues(validated.error.issues,decoded).join("; ")}`);return validated.data},existingHandoff=null;try{existingHandoff=await readPersistedHandoff()}catch(error93){if(error93.code!=="ENOENT")return failure3(`operation read path "${relativeHandoffPath.split(path340.sep).join("/")}": expected bounded JSON matching the persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(existingHandoff){if(!handoffsMatch(existingHandoff))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting handoff content")}else{let serializedHandoff=`${JSON.stringify(handoffRecord,null,2)}
|
|
7177
7177
|
`,serializedHandoffBytes=Buffer.byteLength(serializedHandoff,"utf8");if(serializedHandoffBytes>PR_REVIEW_HANDOFF_MAX_BYTES)return failure3(formatPrReviewRuntimeFieldError("handoff",`a persisted handoff artifact at most ${PR_REVIEW_HANDOFF_MAX_BYTES} UTF-8 bytes`,`${serializedHandoffBytes} bytes`));let created;try{created=await _internals269.atomicCreate(handoffPath,serializedHandoff)}catch(error93){return operationFailure("create",relativeHandoffPath.split(path340.sep).join("/"),"an atomic create-only handoff artifact",error93)}if(!created){let raced;try{raced=await readPersistedHandoff()}catch(error93){return failure3(`operation read path "${relativeHandoffPath.split(path340.sep).join("/")}": expected the concurrently persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(!handoffsMatch(raced))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting concurrent handoff content")}}let alreadyOffered;try{alreadyOffered=(await markPrReviewHandoffComplete(directory,sessionID,resolvedRunId,relativeHandoffPath.split(path340.sep).join("/"))).alreadyOffered}catch(error93){return operationFailure("update",`pr-review/${resolvedRunId}/feedback-consent.json and pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a matching durable consent offer and handoff receipt",error93)}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeHandoffPath.split(path340.sep).join("/"),finding_count:actionableIds.length,already_offered:alreadyOffered,confirmation_command:`/swarm pr-feedback ${parsed.data.handoff.pr_url} continue from .swarm/${relativeHandoffPath.split(path340.sep).join("/")}`},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(PrReviewFindingSchema).min(1).max(1000).optional(),partial_base_coverage:PrReviewPartialBaseCoverageSchema.optional(),handoff:PrReviewHandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID41}from"node:crypto";import fs201 from"node:fs";import path341 from"node:path";var _internals270={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync,markPrReviewTriggerEvaluationComplete};function comparableTriggerReceipt(receipt){return JSON.stringify({...receipt,evaluated_at:void 0,base_verification:void 0})}async function readBoundedTriggerReceipt(destination){let stat23=await fs201.promises.stat(destination);if(!stat23.isFile()||stat23.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt is not a bounded regular file (max ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes)`);let raw=await fs201.promises.readFile(destination,"utf8"),bytes=Buffer.byteLength(raw,"utf8");if(bytes>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt exceeds ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes after read (got ${bytes})`);let decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`trigger evaluation receipt is not valid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsePrReviewTriggerReceipt(decoded),decoded.schema_version!==2)throw Error("trigger evaluation receipt must use schema_version 2");return decoded}async function createTriggerReceipt(destination,content){let parent=path341.dirname(destination),tempPath=path341.join(parent,`.trigger-eval.${randomUUID41()}.tmp`);await fs201.promises.mkdir(parent,{recursive:!0});try{await fs201.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs201.promises.link(tempPath,destination),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs201.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals270.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals270.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals270.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest5=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest5)return digest5}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals270.resolveMergeBase!==resolveExactMergeBase)return _internals270.resolveMergeBase(directory,baseRef,prHeadSha);return _internals270.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(formatPrReviewRuntimeFieldError("pr_head_sha",`"${gateState.prHeadSha}"`,parsed.data.pr_head_sha));try{await assertPrReviewBaseCoverageSettled2(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let artifact=buildPrReviewTriggerReceiptV2({run_id:resolvedRunId,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows,coverage_degradations:coverageDegradations,base_verification:baseVerification}),relativePath2=path341.join("pr-review",resolvedRunId,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let replayed=!1;try{let existing=null;try{existing=await readBoundedTriggerReceipt(destination)}catch(error93){if(error93.code!=="ENOENT")throw error93}if(existing){if(comparableTriggerReceipt(existing)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${resolvedRunId}" with conflicting content`);artifact=existing,replayed=!0}else if(!await createTriggerReceipt(destination,`${JSON.stringify(artifact,null,2)}
|