@unbrained/pm-cli 2026.9.2 → 2026.9.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/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +44 -0
- package/dist/cli/after-command-context-usage.js +16 -3
- package/dist/cli-bundle/bundle-manifest.json +151 -151
- package/dist/cli-bundle/chunks/chunk-6XSKPNCF.js +230 -0
- package/dist/cli-bundle/chunks/chunk-A24WAVE6.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-TAG4VC22.js → chunk-HI6BHPCU.js} +27 -27
- package/dist/cli-bundle/chunks/{chunk-Y7VOMSZT.js → chunk-I2AS367G.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X4RCGLTX.js → chunk-OGBVU67G.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-DTGWEL23.js → chunk-RI4XNOYS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TXW6VL33.js +38 -0
- package/dist/cli-bundle/chunks/{chunk-FZ4Z2J4F.js → chunk-V72UV7QS.js} +76 -79
- package/dist/cli-bundle/chunks/chunk-VGLHECAP.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-T6H5BZCP.js → chunk-X6CMGV6L.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3WICXLVT.js → chunk-YW4QK2G7.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-XYNX4ASQ.js → register-list-query-Z5YYSJJG.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WFQ7MJTX.js → register-mutation-ELSP6I4I.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-JVTI7JPP.js → register-operations-OH7R3ZT4.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-KVNC5KPL.js → register-setup-E2AE72QG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MEASX544.js → chunk-25UJBH4M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SVXJYD6G.js → chunk-3646BZ4W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4YRAVI43.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-53IHPICX.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-5P4HVOWG.js +176 -0
- package/dist/cli-bundle/focused-chunks/chunk-636VVQ7F.js +54 -0
- package/dist/cli-bundle/focused-chunks/{chunk-4O4CJAR6.js → chunk-6PWPQKDN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-7N2TV7WZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-AJR3OP2E.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-B3A6MJYE.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BFDDJ2T2.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BHUIRZWQ.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-JADHHPY6.js +6 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KB5OFSFD.js → chunk-MHKUIPJW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NBMJD6MK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-NSKBLHVI.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BEVHCEWG.js → chunk-P2GOAOQN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-YARWJM2B.js +2 -0
- package/dist/cli-bundle/main.js +15 -15
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +28 -31
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +43 -36
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +10 -10
- package/dist/core/diagnostics/remediation.js +4 -4
- package/dist/core/history/event-classification.d.ts +21 -0
- package/dist/core/history/event-classification.js +109 -0
- package/dist/core/history/event-index.d.ts +14 -3
- package/dist/core/history/event-index.js +543 -88
- package/dist/core/history/history.d.ts +37 -1
- package/dist/core/history/history.js +320 -71
- package/dist/core/history/replay.js +68 -34
- package/dist/core/history/workspace-history.js +7 -6
- package/dist/core/lock/lock.d.ts +32 -2
- package/dist/core/lock/lock.js +161 -20
- package/dist/core/output/output.js +31 -7
- package/dist/core/shared/author.d.ts +3 -1
- package/dist/core/shared/author.js +111 -23
- package/dist/core/shared/time.d.ts +2 -0
- package/dist/core/shared/time.js +8 -2
- package/dist/core/store/item-metadata-query-index.js +5 -5
- package/dist/sdk/context/recency.d.ts +9 -0
- package/dist/sdk/context/recency.js +34 -0
- package/dist/sdk/context/usage-egress.d.ts +9 -0
- package/dist/sdk/context/usage-egress.js +30 -0
- package/dist/sdk/context-intent-contracts.js +7 -3
- package/dist/sdk/context-relevance.d.ts +23 -0
- package/dist/sdk/context-relevance.js +94 -23
- package/dist/sdk/context-signal-store.d.ts +7 -3
- package/dist/sdk/context-signal-store.js +155 -42
- package/dist/sdk/context-usage.d.ts +54 -0
- package/dist/sdk/context-usage.js +245 -16
- package/dist/sdk/environment/agent-environment.d.ts +296 -0
- package/dist/sdk/environment/agent-environment.js +467 -0
- package/dist/sdk/environment/project-runtime-compatibility.d.ts +19 -1
- package/dist/sdk/environment/project-runtime-compatibility.js +118 -21
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +14 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +14 -2
- package/dist/sdk/governance/health.js +13 -44
- package/dist/sdk/governance/merge-receipt-history.d.ts +62 -0
- package/dist/sdk/governance/merge-receipt-history.js +207 -0
- package/dist/sdk/governance/provenance-health.js +9 -3
- package/dist/sdk/history-compact.js +14 -5
- package/dist/sdk/history-redact.js +58 -23
- package/dist/sdk/history-repair.js +16 -6
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.js +6 -2
- package/dist/sdk/init.d.ts +2 -0
- package/dist/sdk/init.js +18 -9
- package/dist/sdk/merge/driver.d.ts +3 -1
- package/dist/sdk/merge/driver.js +9 -9
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +3 -3
- package/dist/sdk/merge/receipts.d.ts +17 -6
- package/dist/sdk/merge/receipts.js +246 -75
- package/dist/sdk/merge/reconcile.d.ts +9 -7
- package/dist/sdk/merge/reconcile.js +175 -12
- package/dist/sdk/merge/three-way.d.ts +22 -2
- package/dist/sdk/merge/three-way.js +92 -25
- package/dist/sdk/query/context.d.ts +3 -1
- package/dist/sdk/query/context.js +21 -9
- package/dist/sdk/query/next.js +18 -9
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +25 -2
- package/dist/sdk/runtime-primitives.d.ts +2 -2
- package/dist/sdk/runtime-primitives.js +4 -4
- package/dist/sdk/runtime.d.ts +1 -0
- package/dist/sdk/runtime.js +17 -26
- package/dist/types.d.ts +27 -0
- package/dist/types.js +2 -2
- package/docs/AGENT_ENVIRONMENTS.md +47 -0
- package/docs/AGENT_PROVENANCE_ADR.md +17 -2
- package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +38 -1
- package/docs/CONTEXT_RELEVANCE.md +44 -1
- package/docs/MERGE_SAFETY.md +119 -23
- package/docs/PERFORMANCE.md +6 -3
- package/docs/README.md +1 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +9 -1
- package/docs/SDK.md +11 -8
- package/docs/SDK_CONTEXT.md +7 -0
- package/docs/SDK_CONTEXT_EVIDENCE_CONTRACTS.md +24 -2
- package/docs/SDK_RUNTIME_BOUNDARIES.md +17 -1
- package/docs/examples/sdk-agent-environment/README.md +14 -0
- package/docs/examples/sdk-agent-environment/package.json +8 -0
- package/docs/examples/sdk-agent-environment/run-agent-environment.mjs +154 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
- package/marketplace.json +2 -2
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +773 -46
- package/dist/cli-bundle/chunks/chunk-GOACULJW.js +0 -13
- package/dist/cli-bundle/chunks/chunk-NOPL37X4.js +0 -205
- package/dist/cli-bundle/chunks/chunk-UDW64J2W.js +0 -8
- package/dist/cli-bundle/chunks/chunk-ZLJIFSOE.js +0 -35
- package/dist/cli-bundle/focused-chunks/chunk-242AXYB2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2FEZ5SKM.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6GCRSLPG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7VATS5QY.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-JEFKLWMM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-MKHG3T76.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-O67VDLOT.js +0 -51
- package/dist/cli-bundle/focused-chunks/chunk-PF3E6Q36.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-QDFJIRKN.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-RMRCQPWU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-S4U5CN5Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-T2LXXSOD.js +0 -158
- package/dist/cli-bundle/focused-chunks/chunk-Z2USIBR2.js +0 -5
|
@@ -1,37 +1,45 @@
|
|
|
1
|
-
import bs from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var Tn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],gc=2,hc=Object.freeze({migration:"schema",validation:"schema"}),jO=Object.freeze({version:gc,capabilities:[...Tn],legacy_aliases:{...hc}}),di=["off","warn","enforce"],ui=["off","warn","enforce"],fi=["none","restricted","strict"];var pi=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"],Er=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function kr(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27c5eac3-4580-5f6f-8ae9-b04d0281766d")}catch{}})();var yc=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],l_=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...yc,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],Se=l_;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var mi=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),_i=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Xt=".agents/pm",Tr="settings.json";var d_=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],u_=["decisions","events","reminders","milestones","meetings","plans"],BO=[...d_,...u_],Ae={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},gi={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},hi=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],Ot={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function bc(e){return e?[...e]:void 0}var ie={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},ux:{deprecation_hints:!0},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...hi],lifecycle_closure_like_blocked_reason_patterns:[...Ot.blocked_reason],lifecycle_closure_like_resolution_patterns:[...Ot.resolution],lifecycle_closure_like_actual_result_patterns:[...Ot.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...gi.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:mi.map(e=>({...e,aliases:bc(e.aliases),roles:bc(e.roles)})),fields:[],workflow:{..._i},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:kr()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},yi={metadata:{},body:""},g={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},GO=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});import{encode as hg}from"@toon-format/toon";import{isDeepStrictEqual as Hc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64223a83-1287-57ac-915d-dbd5e375a6eb")}catch{}})();var bi=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],wc=bi,Jt=["draft","open","in_progress","blocked","closed","canceled"],Sr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Zt=["string","number","boolean","string_array","array","object"],Ar=["create","update","update_many","list","search","calendar","context"],xr=["allow","warn","reject"];var wi=["project","global"];var Cr=["low","medium","high","critical"],Ir=["low","medium","high"];var vc=["minimal","default","strict","custom"];var Or=["daily","weekly","monthly","yearly"],Sn=["mon","tue","wed","thu","fri","sat","sun"];function vi(e){return Sn.indexOf(e)}var Ec=["draft","research","review","approved","executing","paused","completed","superseded"],Rr=["pending","in_progress","completed","blocked","skipped","superseded"],kc=["codex","claude-code","cursor","generic"],Tc=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f6e82c93-54e8-53a7-94df-10a573aae933")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="922e2e27-1499-5466-98e4-322d0d742e40")}catch{}})();var h=class extends Error{exitCode;code;context;constructor(t,n,r={}){super(t),this.name="PmCliError",this.exitCode=n,this.context=r,this.code=r.code}};import f_ from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83232698-197a-5aef-be7c-aa37f3c56822")}catch{}})();function p_(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function m_(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Nr(o))}return n}function Nr(e){let t=p_(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Nr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Nr(r)}return m_(e)}function R(e){return JSON.stringify(Nr(e))}function Sc(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function __(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function g_(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function h_(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!Sc(o,n,r,xe))return!1;return!0}function y_(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!Sc([o,i],n,r,([a,c],[l,d])=>xe(a,l)&&xe(c,d)))return!1;return!0}function b_(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>xe(n,t[r]))}function w_(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!xe(e[i],t[i]))return!1}return!0}var v_=[__,g_,h_,y_,b_];function xe(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of v_){let r=n(e,t);if(r!==void 0)return r}return w_(e,t)}function se(e){return f_.createHash("sha256").update(e,"utf8").digest("hex")}function lt(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function Qt(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import{AsyncLocalStorage as E_}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aacc48ae-e9b2-5c8e-945f-89d05aff48e8")}catch{}})();var k_=new E_;function Ac(){let e=k_.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7887e752-b1b8-5c5e-9dd8-93b41cb757af")}catch{}})();var T_=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function q(){return Ac()??new Date().toISOString()}function Pe(e){return Number.isFinite(Date.parse(e))}function An(e){let t=T_.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,l]=t,[d,u,f,p,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=A_(d,u-1)&&p<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var S_=1e4,Dr=new Map;function xc(e){let t=Dr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Dr.size>=S_&&Qt(Dr),Dr.set(e,n),n}function me(e,t){let n=xc(e),r=xc(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function A_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import Cc from"node:path";import*as ne from"node:fs/promises";import Pr from"node:path";import x_ from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="23fc5fcb-5c80-57ab-8d91-8d15ee35ab53")}catch{}})();var C_=[10,25,50,100];async function dt(e){await ne.mkdir(e,{recursive:!0})}async function B(e){try{return await ne.access(e),!0}catch{return!1}}function xn(e){return H(e)||Rt(e,"ENOTDIR")}function H(e){return Rt(e,"ENOENT")}async function Q(e){try{return await ne.readFile(e,"utf8")}catch(t){if(xn(t))return null;throw t}}async function j(e,t){let n=Pr.dirname(e);await dt(n);let r=Pr.join(n,`.${Pr.basename(e)}.${process.pid}.${Date.now()}.${x_.randomBytes(4).toString("hex")}.tmp`);await ne.writeFile(r,t,"utf8");try{await ne.rename(r,e)}catch(o){if(process.platform==="win32"&&(Rt(o,"EPERM")||Rt(o,"EBUSY"))){let i=o;for(let s of C_){await new Promise(a=>setTimeout(a,s));try{await ne.rename(r,e);return}catch(a){if(i=a,!Rt(a,"EPERM")&&!Rt(a,"EBUSY"))break}}try{await ne.unlink(r)}catch{}throw i}if(Rt(o,"EXDEV")){try{await ne.copyFile(r,e)}finally{try{await ne.unlink(r)}catch{}}return}try{await ne.unlink(r)}catch{}throw o}}async function en(e,t){let n=Pr.dirname(e);await dt(n);let r=await ne.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
-
`,"utf8")}finally{await r.close()}}function
|
|
3
|
-
`}function K_(){return{definitions:[]}}function Y_(){return{statuses:ki}}function X_(){return{fields:[]}}function J_(){return{workflow:Rc}}function Z_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Q_(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function eg(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function tg(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function ng(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function rg(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function be(e,t,n){let r=t?.trim()||n;return Cc.isAbsolute(r)?r:Cc.join(e,r)}async function Mc(e,t){let n=ut(t),r=[{path:be(e,n.files.types,_e.types),seed:K_()},{path:be(e,n.files.statuses,_e.statuses),seed:Y_()},{path:be(e,n.files.fields,_e.fields),seed:X_()},{path:be(e,n.files.workflows,_e.workflows),seed:J_()}],o=[];for(let i of r)await B(i.path)||(await j(i.path,W_(i.seed)),o.push(i.path));return{created_paths:o}}async function Fc(e,t){let n=ut(t),r=[],o=be(e,n.files.types,_e.types),i=be(e,n.files.statuses,_e.statuses),s=be(e,n.files.fields,_e.fields),a=be(e,n.files.workflows,_e.workflows),c,l,d,u,f,p=async(C,k)=>{let S=await Q(C);if(S!==null)return Z_(S,k,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=Q_(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await p(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(l=eg(y),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await p(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=tg(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let E=await p(a,"runtime_schema_workflows_invalid_json");return E!==void 0&&(u=ng(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=rg(E)),{schema:ut({...n,statuses:[...n.statuses,...l??[]],fields:[...n.fields,...d??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function Cn(e,t,n,r=!1){let i=n.map(a=>ye(a)).filter(a=>typeof a=="string").find(a=>e.some(c=>c.id===a));if(r&&i!==void 0)return i;let s=e.find(a=>a.roles.includes(t));return s!==void 0?s.id:i??e[0]?.id}function og(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function ig(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function On(e){let t=ut(e),n=t.statuses.map((E,v)=>Ei(E,v)).filter(E=>E!==null),{aliasToId:r,byId:o}=og(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:l,terminalStatuses:d}=ig(n),u=t.workflow,f=ye(u.open_status)??Cn(n,"default_open",["open","in_progress",Jt[0]]),p=ye(u.in_progress_status)??Cn(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??Cn(n,"blocked",["blocked"]),y=ye(u.close_status)??Cn(n,"default_close",["closed","done","complete"]),b=ye(u.canceled_status)??Cn(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:d,terminal_done_statuses:l,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:p,blocked_status:_,close_status:y,canceled_status:b}}function tn(e,t){let n=qe(e);if(n)return t.alias_to_id.get(n)}function Ti(e){let t=ut(e),n=new Map,r=t.fields.map(c=>Lc(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,l)=>c.key.localeCompare(l.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let l of c.cli_aliases)s.set(l,c);for(let l of c.commands){let d=a.get(l)??[];d.push(c),a.set(l,d)}}for(let[c,l]of a.entries())l.sort((d,u)=>d.key.localeCompare(u.key)),a.set(c,l);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function Si(e,t){let n=tn(e,t);return n?t.terminal_statuses.has(n):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91a3969e-59b3-506e-9349-ca08e73a1228")}catch{}})();var sg=16;function Uc(e){return Array.isArray(e)?e.flatMap(t=>Uc(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function $c(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new h(`${t} must be one of true|false|1|0|yes|no`,g.USAGE)}function jc(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new h(`${t} must be a number`,g.USAGE);return r}function ag(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new h(`${t} must be valid JSON ${n}`,g.USAGE)}function cg(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function lg(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!cg(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!An(e))return`${n} must be an RFC 3339 date-time`}}function dg(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=$r(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function ug(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=$r(s,a,`${n}.${i}`,r+1);if(c)return c}}function $r(e,t,n,r=0){if(r>sg)return`${n} value schema exceeds maximum depth`;let o=lg(e,t,n);if(o)return o;let i=dg(e,t,n,r);if(i)return i;let s=ug(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if($r(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function Nt(e,t,n){if(!e.value_schema||t===void 0)return t;let r=$r(t,e.value_schema,n);if(r)throw new h(r,g.USAGE);return t}function jr(e,t,n){let r=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object"){let i=Array.isArray(t)?t[t.length-1]:t;return i===void 0?void 0:Nt(e,ag(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=Uc(t);return e.type==="number"?Nt(e,i.map(s=>jc(s,r)),r):e.type==="boolean"?Nt(e,i.map(s=>$c(s,r)),r):Nt(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?Nt(e,jc(o,r),r):e.type==="boolean"?Nt(e,$c(o,r),r):Nt(e,typeof o=="string"?o:String(o),r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var nn=1,Ur=1;function zc(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=nn?t:nn}function qc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=nn))return e}function fg(e,t=Ur){return e<t?"outdated":e>t?"ahead":"current"}function Bc(e,t=Ur){let n=[],r=[];for(let o of e){let i=fg(o.version,t);i==="outdated"?n.push(o.ref):i==="ahead"&&r.push(o.ref)}return{outdated:n.sort((o,i)=>o.localeCompare(i)),ahead:r.sort((o,i)=>o.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7501aa2-d3d9-5fbe-a1c0-d4bc145f5563")}catch{}})();var pg={"in-progress":"in_progress",cancelled:"canceled"};function Dt(e,t){if(t){let o=tn(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=pg[n]??n;if(Jt.includes(r))return r}import{decode as mg}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2840e12e-7444-5d36-9f54-5a56267bbb75")}catch{}})();function Ai(e){return{value:mg(e),usedScalarBracketEscape:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fedb7b50-6946-589d-b240-9f074e09e467")}catch{}})();var _g=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function gg(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(_g);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Le(e){return gg(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function Rn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function de(e){return Rn(e)??void 0}function Je(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Gc(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="051655a4-8ba7-5118-9758-d9ca377fa7e4")}catch{}})();var Oi=new Set(["schema","tracker","auto"]),Kc=new Set(["source","isolated","snapshot"]),yg=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),bg=new Set(["passed","failed","stopped","canceled"]),wg=new Set(Rr);function sn(e){return e.replaceAll("\\","/")}function Yc(e){for(let t of e)if(t!==0)return t;return 0}function qr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Xc=["id","title","description","created_at","updated_at"],vg=new Set(Se);function Jc(e){if(e?.schema)return{statusRegistry:On(e.schema),fieldRegistry:Ti(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Eg(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function ft(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new h(`Invalid item metadata: ${e}`,g.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function Pn(e,t){throw new h(t,g.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Zc(e){let t=new Set(vg);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function I(e,t){e||ft(t)}function Ln(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&ft(t),e}function xi(e,t){let n=e[t];I(typeof n=="string",`${t} must be a string`),I(Pe(n),`${t} must be a valid ISO timestamp`)}function Vc(e,t,n){let r=e[t];r!==void 0&&I(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Ri(e,t,n){let r=e[t];r!==void 0&&(I(typeof r=="string",`${n} must be a string`),I(Pe(r),`${n} must be a valid ISO timestamp`))}function kg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){I(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();I(Sn.includes(n),`event.recurrence.by_weekday entries must be one of: ${Sn.join(", ")}`)}}}function Tg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)I(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Sg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)I(typeof t=="string","event.recurrence.exdates entries must be strings"),I(Pe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Ag(e){let t=Ln(e,"event.recurrence must be an object");I(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();I(Or.includes(n),`event.recurrence.freq must be one of: ${Or.join(", ")}`),Vc(t,"interval","event.recurrence.interval"),Vc(t,"count","event.recurrence.count"),Ri(t,"until","event.recurrence.until"),kg(t.by_weekday),Tg(t.by_month_day),Sg(t.exdates)}function xg(e){for(let r of Xc)I(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;I(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&I(typeof n=="number"&&Number.isInteger(n)&&n>=nn,`pm_format_version must be an integer >= ${nn}`),t}function Cg(e,t){let n=e.status;I(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Dt(n,r),i=r?r.definitions.map(s=>s.id):[...Jt];I(o!==void 0,`status must be one of: ${i.join(", ")}`)}function Ig(e){let t=e.priority;I(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;I(Array.isArray(n),"tags must be an array");for(let r of n)I(typeof r=="string","tags entries must be strings")}function Og(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){I(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||Ir.includes(n);I(r,`confidence string value must be one of: ${[...Ir,"med"].join(", ")}`);return}I(!1,"confidence must be a number or string")}}function Rg(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&ft("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Cr.includes(n);I(r,`severity value must be one of: ${[...Cr,"med"].join(", ")}`)}function Ng(e){e.regression!==void 0&&typeof e.regression!="boolean"&&ft("regression must be a boolean")}function Dg(e){let t=e.reminders;if(t!==void 0){I(Array.isArray(t),"reminders must be an array");for(let n of t){let r=Ln(n,"reminders entries must be objects");I(typeof r.at=="string","reminder.at must be a string"),I(Pe(r.at),"reminder.at must be a valid ISO timestamp"),I(typeof r.text=="string","reminder.text must be a string"),I(r.text.trim().length>0,"reminder.text must not be empty")}}}function Pg(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(I(typeof e[t]=="string",`event.${t} must be a string`),I(e[t].trim().length>0,`event.${t} must not be empty`))}function Lg(e){e.recurrence!==void 0&&(Ag(e.recurrence),e.recurrence.until!==void 0&&I(me(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Mg(e){let t=Ln(e,"events entries must be objects");I(typeof t.start_at=="string","event.start_at must be a string"),I(Pe(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(I(typeof t.end_at=="string","event.end_at must be a string"),I(Pe(t.end_at),"event.end_at must be a valid ISO timestamp"),I(me(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Pg(t),t.all_day!==void 0&&I(typeof t.all_day=="boolean","event.all_day must be a boolean"),Lg(t)}function Fg(e){let t=e.events;if(t!==void 0){I(Array.isArray(t),"events must be an array");for(let n of t)Mg(n)}}function $g(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&I(typeof n=="string",`${t} must be a string`)}}function jg(e){let t=e.type_options;if(t===void 0)return;let n=Ln(t,"type_options must be an object");for(let[r,o]of Object.entries(n))I(r.trim().length>0,"type_options keys must be non-empty"),I(typeof o=="string","type_options values must be strings"),I(o.trim().length>0,"type_options values must be non-empty strings")}function Ug(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Eg(r,t)&&ft(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=jr(r,o,`metadata field "${r.metadata_key}"`)}catch(i){ft(String(i?.message).replace(/^Invalid\s+/u,""))}}}function zg(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Zc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?ft(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ni(e,t){let n=Ln(e,"item metadata must be an object"),r=xg(n);Cg(n,t),Ig(n),Og(n),Rg(n),Ng(n),xi(n,"created_at"),xi(n,"updated_at"),n.deadline!==void 0&&xi(n,"deadline"),Dg(n),Fg(n),Ri(n,"closed_at","closed_at"),Ri(n,"completed_at","completed_at"),$g(n),jg(n),Ug(n,r,t),zg(n,t)}function qg(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=me(t.created_at,n.created_at);if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function Ci(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=me(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function Bg(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=me(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function Gg(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Or.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Sn.includes(s)))).sort((s,a)=>vi(s)-vi(a)),r=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>Pe(s)))).sort((s,a)=>me(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:n.length>0?n:void 0,by_month_day:r.length>0?r:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function Hg(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(Vg).sort(Wg)}function Vg(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:Gg(e.recurrence)};return qr(t),t}function Wg(e,t){return Yc([me(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function Kg(e){if(!(!e||e.length===0))return e.map(t=>({path:sn(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Yg(e){if(!e||e.length===0)return;let t=e.map(Qg).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>Yc([me(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function rn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Xg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ii(e){return typeof e=="string"?e:""}function Jg(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function zr(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function Zg(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:zr(n.requested_pm_context_mode,Oi),pm_context_mode:zr(n.pm_context_mode,Oi),workspace_context_mode:zr(n.workspace_context_mode,Kc),trust_reason:zr(n.trust_reason,yg)}));return t.length>0?t:void 0}function Qg(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=bg.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ii(e.started_at),finished_at:Ii(e.finished_at),recorded_at:Ii(e.recorded_at),attempt:Xg(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:rn(e.passed)??0,failed:rn(e.failed)??0,skipped:rn(e.skipped)??0,items:rn(e.items),linked_tests:rn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Jg(e.measurements),executions:Zg(e.executions)};return qr(o),o}function eh(e){if(!(!Array.isArray(e)||e.length===0))return e.map(ih)}function Nn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Pi(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Li(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Wc(e){if(!Pi(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Li(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function th(e){if(!Pi(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Li(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function nh(e){let t=e?.trim().toLowerCase();if(!(!t||!Oi.has(t)))return t}function rh(e){let t=e?.trim().toLowerCase();if(!(!t||!Kc.has(t)))return t}function oh(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Pi(e))return{provenance_invalid:!0};let n=x(e.author),r=x(e.created_at),o=e.source_kind;return!n||!r||!Pe(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:x(e.source_ref)}}}function ih(e){let t={command:e.command?.trim()||void 0,path:e.path?sn(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:nh(e.pm_context_mode),workspace_context_mode:rh(e.workspace_context_mode),...oh(e.provenance,e.provenance_invalid),env_set:Wc(e.env_set),env_clear:Nn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:Nn(e.assert_stdout_contains),assert_stdout_regex:Nn(e.assert_stdout_regex),assert_stderr_contains:Nn(e.assert_stderr_contains),assert_stderr_regex:Nn(e.assert_stderr_regex),assert_stdout_min_lines:rn(e.assert_stdout_min_lines),assert_json_field_equals:Wc(e.assert_json_field_equals),assert_json_field_gte:th(e.assert_json_field_gte),note:e.note?.trim()||void 0};return qr(t),t}function sh(e){if(!(!e||e.length===0))return[...e].map(t=>({path:sn(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function x(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function ah(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.id),i=x(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=x(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function ch(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function lh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.command),i=x(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=sn(i));let a=x(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function dh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function uh(e){if(e===null||typeof e!="object")return;let t=e,n=x(t.id),r=x(t.title),o=x(t.status),i=o&&wg.has(o)?o:void 0,s=Gc(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let l={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return fh(l,t),l}function fh(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=x(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",ah],["files","files",ch],["tests","tests",lh],["docs","docs",dh]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function ph(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=uh(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function mh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=x(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=x(r.rationale);c&&(a.rationale=c);let l=x(r.evidence);l&&(a.evidence=l);let d=x(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function _h(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=x(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=x(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function gh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.text);if(!o)continue;let i={text:o},s=x(r.command);s&&(i.command=s);let a=x(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function hh(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function on(e){let t=0;for(;t<e.length&&e[t]===`
|
|
4
|
-
`;)t+=1;return e.slice(t).trimEnd()}function
|
|
5
|
-
`,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function
|
|
1
|
+
import pl from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var Ve=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],mi=2,xa=Object.freeze({migration:"schema",validation:"schema"}),_i=Object.freeze({version:mi,capabilities:[...Ve],legacy_aliases:{...xa}}),gi=["off","warn","enforce"],hi=["off","warn","enforce"],yi=["none","restricted","strict"],Ku=["block","warn"],wi=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"],er=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function bi(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27c5eac3-4580-5f6f-8ae9-b04d0281766d")}catch{}})();var Ju=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],tv=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...Ju,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],Le=tv;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var Ta=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),Aa=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),tr=".agents/pm",vi="settings.json";var Ia=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],nv=["decisions","events","reminders","milestones","meetings","plans"],Y1=[...Ia,...nv],Oe={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},Ca={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},Oa=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],vn={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function Yu(e){return e?[...e]:void 0}var he={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},ux:{deprecation_hints:!0},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...Oa],lifecycle_closure_like_blocked_reason_patterns:[...vn.blocked_reason],lifecycle_closure_like_resolution_patterns:[...vn.resolution],lifecycle_closure_like_actual_result_patterns:[...vn.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...Ca.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:Ta.map(e=>({...e,aliases:Yu(e.aliases),roles:Yu(e.roles)})),fields:[],workflow:{...Aa},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:bi()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},Ra={metadata:{},body:""},h={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},X1=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});import{encode as ck}from"@toon-format/toon";import{isDeepStrictEqual as Sf}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4ee067ac-f28d-5411-9ac7-c92112384a64")}catch{}})();var Na=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],Xu=Na,nr=["draft","open","in_progress","blocked","closed","canceled"],rr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Wt=["string","number","boolean","string_array","array","object"],or=["create","update","update_many","list","search","calendar","context"],ki=["allow","warn","reject"];var Da=["project","global"];var Ei=["low","medium","high","critical"],Si=["low","medium","high"];var Zu=["minimal","default","strict","custom"];var xi=["daily","weekly","monthly","yearly"],zr=["mon","tue","wed","thu","fri","sat","sun"];function Pa(e){return zr.indexOf(e)}var Qu=["draft","research","review","approved","executing","paused","completed","superseded"],Ti=["pending","in_progress","completed","blocked","skipped","superseded"],ef=["codex","claude-code","cursor","generic"],tf=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f6e82c93-54e8-53a7-94df-10a573aae933")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="922e2e27-1499-5466-98e4-322d0d742e40")}catch{}})();var w=class extends Error{exitCode;code;context;constructor(t,n,r={}){super(t),this.name="PmCliError",this.exitCode=n,this.context=r,this.code=r.code}};import rv from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83232698-197a-5aef-be7c-aa37f3c56822")}catch{}})();function ov(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function iv(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Ai(o))}return n}function Ai(e){let t=ov(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Ai(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Ai(r)}return iv(e)}function N(e){return JSON.stringify(Ai(e))}function nf(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function sv(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function av(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function cv(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!nf(o,n,r,rt))return!1;return!0}function lv(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!nf([o,i],n,r,([a,c],[l,d])=>rt(a,l)&&rt(c,d)))return!1;return!0}function dv(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>rt(n,t[r]))}function uv(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!rt(e[i],t[i]))return!1}return!0}var fv=[sv,av,cv,lv,dv];function rt(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of fv){let r=n(e,t);if(r!==void 0)return r}return uv(e,t)}function ye(e){return rv.createHash("sha256").update(e,"utf8").digest("hex")}function Kt(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function ir(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import{AsyncLocalStorage as pv}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aacc48ae-e9b2-5c8e-945f-89d05aff48e8")}catch{}})();var mv=new pv;function rf(){let e=mv.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fb1102d4-1beb-5de8-87e6-af2efebafe39")}catch{}})();var _v=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function F(){return rf()??new Date().toISOString()}function dt(e){return Number.isFinite(Date.parse(e))}function Ot(e){let t=_v.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,l]=t,[d,u,f,p,m,g]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=hv(d,u-1)&&p<=23&&m<=59&&g<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}function Ci(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return Ot(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var gv=1e4,Ii=new Map;function of(e){let t=Ii.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Ii.size>=gv&&ir(Ii),Ii.set(e,n),n}function me(e,t){let n=of(e),r=of(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function hv(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import sf from"node:path";import*as _e from"node:fs/promises";import Oi from"node:path";import yv from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="23fc5fcb-5c80-57ab-8d91-8d15ee35ab53")}catch{}})();var wv=[10,25,50,100];async function Jt(e){await _e.mkdir(e,{recursive:!0})}async function U(e){try{return await _e.access(e),!0}catch{return!1}}function ut(e){return j(e)||kn(e,"ENOTDIR")}function j(e){return kn(e,"ENOENT")}async function Z(e){try{return await _e.readFile(e,"utf8")}catch(t){if(ut(t))return null;throw t}}async function H(e,t){let n=Oi.dirname(e);await Jt(n);let r=Oi.join(n,`.${Oi.basename(e)}.${process.pid}.${Date.now()}.${yv.randomBytes(4).toString("hex")}.tmp`);await _e.writeFile(r,t,"utf8");try{await _e.rename(r,e)}catch(o){if(process.platform==="win32"&&(kn(o,"EPERM")||kn(o,"EBUSY"))){let i=o;for(let s of wv){await new Promise(a=>setTimeout(a,s));try{await _e.rename(r,e);return}catch(a){if(i=a,!kn(a,"EPERM")&&!kn(a,"EBUSY"))break}}try{await _e.unlink(r)}catch{}throw i}if(kn(o,"EXDEV")){try{await _e.copyFile(r,e)}finally{try{await _e.unlink(r)}catch{}}return}try{await _e.unlink(r)}catch{}throw o}}async function Hr(e,t){let n=Oi.dirname(e);await Jt(n);let r=await _e.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
+
`,"utf8")}finally{await r.close()}}function kn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d6056922-237d-525a-b354-687493a4e123")}catch{}})();var bv=2e3,Ri=new Map;function we(e){if(typeof e!="string")return"";let t=Ri.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Ri.size>=bv&&ir(Ri),Ri.set(e,n),n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="633ef301-42a3-5b73-a4ed-7af0e0e40371")}catch{}})();var xe=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),lf=Aa,Gr=Ta,vv=["create","update"],kv=new Set(rr),Ev=new Set(Wt),Sv=new Set(or),xv=new Set(ki),Tv=new Set(["string","number","boolean","array","object"]),Av=16;function df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Iv=[e=>e.type===void 0||typeof e.type=="string"&&Tv.has(e.type),e=>!Object.hasOwn(e,"const")||Di(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Di(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||df(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Di(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=Array.isArray(e)?e.every(r=>Di(r,t)):Object.values(e).every(r=>Di(r,t));return t.delete(e),n}function Ni(e,t=0,n=new Set){if(!df(e)||t>Av||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,l=r.required,d=r.min_length,u=r.min_items,f=r.format,p=r.additional_properties;if(!Iv.every(v=>v(r))){n.delete(e);return}let m=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,A])=>[v,Ni(A,t+1,n)])),g=c===void 0?void 0:Ni(c,t+1,n),y=s===void 0?void 0:s.map(v=>Ni(v,t+1,n));if([...Object.values(m??{}),...c===void 0?[]:[g],...y??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:d,min_items:u,format:f,properties:m,required:l===void 0?void 0:[...new Set(l)],additional_properties:p,items:g,one_of:y}).filter(([,v])=>v!==void 0))}function Br(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function We(e){if(typeof e!="string"||e.length===0)return;let t=we(e);return t.length>0?t:void 0}function Cv(e){return e.startsWith("--")?e.slice(2):e}function af(e){return typeof e=="string"?Cv(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function uf(e){return e.replaceAll("_","-")}function La(e,t){let n=We(e.id);if(!n)return null;let r=[...new Set(Br(e.aliases).map(we).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=Br(e.roles).filter(a=>kv.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function Ov(e){return{draft_status:We(e?.draft_status),open_status:We(e?.open_status),in_progress_status:We(e?.in_progress_status),blocked_status:We(e?.blocked_status),close_status:We(e?.close_status),canceled_status:We(e?.canceled_status)}}function ff(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=we(t[0]),r=we(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function Rv(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)ff(n,r);return{typeKey:t.toLowerCase(),record:n}}function Nv(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=Rv(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)ff(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function pf(e){let t=we(e.key??"");if(!t)return null;let n=we(e.metadata_key??e.front_matter_key??t),r=af(e.cli_flag??uf(t));if(!r)return null;let o=Br(e.cli_aliases).map(u=>af(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=Ev.has(i)?i:"string",a=(()=>{let u=Br(e.commands).filter(f=>Sv.has(f));return u.length>0?u:[...vv]})(),c=e.description?.trim(),l=Br(e.required_types),d=e.value_schema===void 0?void 0:Ni(e.value_schema);return e.value_schema!==void 0&&d===void 0?null:{key:t,metadata_key:n,cli_flag:r,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:[e.repeatable===!0,s==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:l,allow_unset:e.allow_unset!==!1,value_schema:d}}function Dv(e){let t=new Map;for(let[r,o]of e.entries()){let i=La(o,r);i&&t.set(i.id,i)}let n=cf([...t.values()]);return n.length>0?n:cf(Gr.map((r,o)=>La(r,o)).filter(r=>r!==null))}function cf(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function Pv(e){let t=new Map;for(let n of e??[]){let r=pf(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function Lv(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function Mv(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==uf(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function $v(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return xv.has(t)?t:"allow"}function _t(e){let t={...xe,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:Gr,r=Dv(n),o=Pv(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(Lv),fields:o.map(Mv),workflow:{...lf,...Ov(e?.workflow)},type_workflows:Nv(e?.type_workflows),unknown_field_policy:$v(e?.unknown_field_policy)}}function Fv(e){return`${JSON.stringify(e,null,2)}
|
|
3
|
+
`}function jv(){return{definitions:[]}}function Uv(){return{statuses:Gr}}function zv(){return{fields:[]}}function Hv(){return{workflow:lf}}function qv(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Bv(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function Gv(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Vv(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Wv(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function Kv(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function Re(e,t,n){let r=t?.trim()||n;return sf.isAbsolute(r)?r:sf.join(e,r)}async function mf(e,t){let n=_t(t),r=[{path:Re(e,n.files.types,xe.types),seed:jv()},{path:Re(e,n.files.statuses,xe.statuses),seed:Uv()},{path:Re(e,n.files.fields,xe.fields),seed:zv()},{path:Re(e,n.files.workflows,xe.workflows),seed:Hv()}],o=[];for(let i of r)await U(i.path)||(await H(i.path,Fv(i.seed)),o.push(i.path));return{created_paths:o}}async function _f(e,t){let n=_t(t),r=[],o=Re(e,n.files.types,xe.types),i=Re(e,n.files.statuses,xe.statuses),s=Re(e,n.files.fields,xe.fields),a=Re(e,n.files.workflows,xe.workflows),c,l,d,u,f,p=async(A,I)=>{let x=await Z(A);if(x!==null)return qv(x,I,r)},m=await p(o,"runtime_schema_types_invalid_json");m!==void 0&&(c=Bv(m),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let g=await p(i,"runtime_schema_statuses_invalid_json");g!==void 0&&(l=Gv(g),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let y=await p(s,"runtime_schema_fields_invalid_json");y!==void 0&&(d=Vv(y),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let b=await p(a,"runtime_schema_workflows_invalid_json");return b!==void 0&&(u=Wv(b),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=Kv(b)),{schema:_t({...n,statuses:[...n.statuses,...l??[]],fields:[...n.fields,...d??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function qr(e,t,n,r=!1){let i=n.map(a=>We(a)).filter(a=>typeof a=="string").find(a=>e.some(c=>c.id===a));if(r&&i!==void 0)return i;let s=e.find(a=>a.roles.includes(t));return s!==void 0?s.id:i??e[0]?.id}function Jv(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function Yv(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Rt(e){let t=_t(e),n=t.statuses.map((b,v)=>La(b,v)).filter(b=>b!==null),{aliasToId:r,byId:o}=Jv(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:l,terminalStatuses:d}=Yv(n),u=t.workflow,f=We(u.open_status)??qr(n,"default_open",["open","in_progress",nr[0]]),p=We(u.in_progress_status)??qr(n,"active",["in_progress","in-progress",f],!0),m=We(u.blocked_status)??qr(n,"blocked",["blocked"]),g=We(u.close_status)??qr(n,"default_close",["closed","done","complete"]),y=We(u.canceled_status)??qr(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:d,terminal_done_statuses:l,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:p,blocked_status:m,close_status:g,canceled_status:y}}function sr(e,t){let n=we(e);if(n)return t.alias_to_id.get(n)}function Pi(e){let t=_t(e),n=new Map,r=t.fields.map(c=>pf(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,l)=>c.key.localeCompare(l.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let l of c.cli_aliases)s.set(l,c);for(let l of c.commands){let d=a.get(l)??[];d.push(c),a.set(l,d)}}for(let[c,l]of a.entries())l.sort((d,u)=>d.key.localeCompare(u.key)),a.set(c,l);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function Ma(e,t){let n=sr(e,t);return n?t.terminal_statuses.has(n):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91a3969e-59b3-506e-9349-ca08e73a1228")}catch{}})();var Xv=16;function yf(e){return Array.isArray(e)?e.flatMap(t=>yf(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function gf(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new w(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function hf(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new w(`${t} must be a number`,h.USAGE);return r}function Zv(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new w(`${t} must be valid JSON ${n}`,h.USAGE)}function Qv(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function ek(e,t,n){if(t.const!==void 0&&N(e)!==N(t.const))return`${n} must equal ${N(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>N(r)===N(e)))return`${n} must be one of ${t.enum.map(r=>N(r)).join("|")}`;if(!Qv(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!Ot(e))return`${n} must be an RFC 3339 date-time`}}function tk(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Li(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function nk(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=Li(s,a,`${n}.${i}`,r+1);if(c)return c}}function Li(e,t,n,r=0){if(r>Xv)return`${n} value schema exceeds maximum depth`;let o=ek(e,t,n);if(o)return o;let i=tk(e,t,n,r);if(i)return i;let s=nk(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Li(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function En(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Li(t,e.value_schema,n);if(r)throw new w(r,h.USAGE);return t}function Mi(e,t,n){let r=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object"){let i=Array.isArray(t)?t[t.length-1]:t;return i===void 0?void 0:En(e,Zv(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=yf(t);return e.type==="number"?En(e,i.map(s=>hf(s,r)),r):e.type==="boolean"?En(e,i.map(s=>gf(s,r)),r):En(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?En(e,hf(o,r),r):e.type==="boolean"?En(e,gf(o,r),r):En(e,typeof o=="string"?o:String(o),r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var ar=1,$i=1;function Fi(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=ar?t:ar}function wf(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=ar))return e}function rk(e,t=$i){return e<t?"outdated":e>t?"ahead":"current"}function ji(e,t=$i){let n=[],r=[];for(let o of e){let i=rk(o.version,t);i==="outdated"?n.push(o.ref):i==="ahead"&&r.push(o.ref)}return{outdated:n.sort((o,i)=>o.localeCompare(i)),ahead:r.sort((o,i)=>o.localeCompare(i))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7501aa2-d3d9-5fbe-a1c0-d4bc145f5563")}catch{}})();var ok={"in-progress":"in_progress",cancelled:"canceled"};function Yt(e,t){if(t){let o=sr(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=ok[n]??n;if(nr.includes(r))return r}function bf(e,t){return Yt(e,t)??e}function $a(e,t){return t.terminal_statuses.has(bf(e,t))}import{decode as ik}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2840e12e-7444-5d36-9f54-5a56267bbb75")}catch{}})();function Fa(e){return{value:ik(e),usedScalarBracketEscape:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fedb7b50-6946-589d-b240-9f074e09e467")}catch{}})();var sk=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function ak(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(sk);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Me(e){return ak(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function q(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ae(e){return q(e)??void 0}function Vr(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function cr(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function ne(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function ja(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}function kf(e){let t=ja(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function Sn(e){return typeof e!="object"||e===null?null:e}function vf(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Ef(e){let t=vf(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=vf(t.default);return typeof n?.activate=="function"?n:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="051655a4-8ba7-5118-9758-d9ca377fa7e4")}catch{}})();var qa=new Set(["schema","tracker","auto"]),Af=new Set(["source","isolated","snapshot"]),lk=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),dk=new Set(["passed","failed","stopped","canceled"]),uk=new Set(Ti);function ur(e){return e.replaceAll("\\","/")}function If(e){for(let t of e)if(t!==0)return t;return 0}function zi(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Cf=["id","title","description","created_at","updated_at"],fk=new Set(Le);function Of(e){if(e?.schema)return{statusRegistry:Rt(e.schema),fieldRegistry:Pi(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function pk(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Xt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new w(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function Jr(e,t){throw new w(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Rf(e){let t=new Set(fk);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function D(e,t){e||Xt(t)}function Yr(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Xt(t),e}function Ua(e,t){let n=e[t];D(typeof n=="string",`${t} must be a string`),D(dt(n),`${t} must be a valid ISO timestamp`)}function xf(e,t,n){let r=e[t];r!==void 0&&D(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Ba(e,t,n){let r=e[t];r!==void 0&&(D(typeof r=="string",`${n} must be a string`),D(dt(r),`${n} must be a valid ISO timestamp`))}function mk(e){if(e!==void 0){D(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){D(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();D(zr.includes(n),`event.recurrence.by_weekday entries must be one of: ${zr.join(", ")}`)}}}function _k(e){if(e!==void 0){D(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)D(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function gk(e){if(e!==void 0){D(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)D(typeof t=="string","event.recurrence.exdates entries must be strings"),D(dt(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function hk(e){let t=Yr(e,"event.recurrence must be an object");D(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();D(xi.includes(n),`event.recurrence.freq must be one of: ${xi.join(", ")}`),xf(t,"interval","event.recurrence.interval"),xf(t,"count","event.recurrence.count"),Ba(t,"until","event.recurrence.until"),mk(t.by_weekday),_k(t.by_month_day),gk(t.exdates)}function yk(e){for(let r of Cf)D(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;D(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&D(typeof n=="number"&&Number.isInteger(n)&&n>=ar,`pm_format_version must be an integer >= ${ar}`),t}function wk(e,t){let n=e.status;D(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Yt(n,r),i=r?r.definitions.map(s=>s.id):[...nr];D(o!==void 0,`status must be one of: ${i.join(", ")}`)}function bk(e){let t=e.priority;D(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;D(Array.isArray(n),"tags must be an array");for(let r of n)D(typeof r=="string","tags entries must be strings")}function vk(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){D(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||Si.includes(n);D(r,`confidence string value must be one of: ${[...Si,"med"].join(", ")}`);return}D(!1,"confidence must be a number or string")}}function kk(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Xt("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Ei.includes(n);D(r,`severity value must be one of: ${[...Ei,"med"].join(", ")}`)}function Ek(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Xt("regression must be a boolean")}function Sk(e){let t=e.reminders;if(t!==void 0){D(Array.isArray(t),"reminders must be an array");for(let n of t){let r=Yr(n,"reminders entries must be objects");D(typeof r.at=="string","reminder.at must be a string"),D(dt(r.at),"reminder.at must be a valid ISO timestamp"),D(typeof r.text=="string","reminder.text must be a string"),D(r.text.trim().length>0,"reminder.text must not be empty")}}}function xk(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(D(typeof e[t]=="string",`event.${t} must be a string`),D(e[t].trim().length>0,`event.${t} must not be empty`))}function Tk(e){e.recurrence!==void 0&&(hk(e.recurrence),e.recurrence.until!==void 0&&D(me(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Ak(e){let t=Yr(e,"events entries must be objects");D(typeof t.start_at=="string","event.start_at must be a string"),D(dt(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(D(typeof t.end_at=="string","event.end_at must be a string"),D(dt(t.end_at),"event.end_at must be a valid ISO timestamp"),D(me(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),xk(t),t.all_day!==void 0&&D(typeof t.all_day=="boolean","event.all_day must be a boolean"),Tk(t)}function Ik(e){let t=e.events;if(t!==void 0){D(Array.isArray(t),"events must be an array");for(let n of t)Ak(n)}}function Ck(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&D(typeof n=="string",`${t} must be a string`)}}function Ok(e){let t=e.type_options;if(t===void 0)return;let n=Yr(t,"type_options must be an object");for(let[r,o]of Object.entries(n))D(r.trim().length>0,"type_options keys must be non-empty"),D(typeof o=="string","type_options values must be strings"),D(o.trim().length>0,"type_options values must be non-empty strings")}function Rk(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){pk(r,t)&&Xt(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=Mi(r,o,`metadata field "${r.metadata_key}"`)}catch(i){Xt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Nk(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Rf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Xt(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ga(e,t){let n=Yr(e,"item metadata must be an object"),r=yk(n);wk(n,t),bk(n),vk(n),kk(n),Ek(n),Ua(n,"created_at"),Ua(n,"updated_at"),n.deadline!==void 0&&Ua(n,"deadline"),Sk(n),Ik(n),Ba(n,"closed_at","closed_at"),Ba(n,"completed_at","completed_at"),Ck(n),Ok(n),Rk(n,r,t),Nk(n,t)}function Dk(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=me(t.created_at,n.created_at);if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function za(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=me(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function Pk(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=me(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function Lk(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!xi.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>zr.includes(s)))).sort((s,a)=>Pa(s)-Pa(a)),r=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>dt(s)))).sort((s,a)=>me(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:n.length>0?n:void 0,by_month_day:r.length>0?r:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function Mk(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map($k).sort(Fk)}function $k(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:Lk(e.recurrence)};return zi(t),t}function Fk(e,t){return If([me(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function jk(e){if(!(!e||e.length===0))return e.map(t=>({path:ur(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Uk(e){if(!e||e.length===0)return;let t=e.map(Bk).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>If([me(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function lr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function zk(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ha(e){return typeof e=="string"?e:""}function Hk(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function Ui(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function qk(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:Ui(n.requested_pm_context_mode,qa),pm_context_mode:Ui(n.pm_context_mode,qa),workspace_context_mode:Ui(n.workspace_context_mode,Af),trust_reason:Ui(n.trust_reason,lk)}));return t.length>0?t:void 0}function Bk(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=dk.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ha(e.started_at),finished_at:Ha(e.finished_at),recorded_at:Ha(e.recorded_at),attempt:zk(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:lr(e.passed)??0,failed:lr(e.failed)??0,skipped:lr(e.skipped)??0,items:lr(e.items),linked_tests:lr(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Hk(e.measurements),executions:qk(e.executions)};return zi(o),o}function Gk(e){if(!(!Array.isArray(e)||e.length===0))return e.map(Yk)}function Wr(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Wa(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ka(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Tf(e){if(!Wa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Ka(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Vk(e){if(!Wa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Ka(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Wk(e){let t=e?.trim().toLowerCase();if(!(!t||!qa.has(t)))return t}function Kk(e){let t=e?.trim().toLowerCase();if(!(!t||!Af.has(t)))return t}function Jk(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Wa(e))return{provenance_invalid:!0};let n=O(e.author),r=O(e.created_at),o=e.source_kind;return!n||!r||!dt(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:O(e.source_ref)}}}function Yk(e){let t={command:e.command?.trim()||void 0,path:e.path?ur(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:Wk(e.pm_context_mode),workspace_context_mode:Kk(e.workspace_context_mode),...Jk(e.provenance,e.provenance_invalid),env_set:Tf(e.env_set),env_clear:Wr(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:Wr(e.assert_stdout_contains),assert_stdout_regex:Wr(e.assert_stdout_regex),assert_stderr_contains:Wr(e.assert_stderr_contains),assert_stderr_regex:Wr(e.assert_stderr_regex),assert_stdout_min_lines:lr(e.assert_stdout_min_lines),assert_json_field_equals:Tf(e.assert_json_field_equals),assert_json_field_gte:Vk(e.assert_json_field_gte),note:e.note?.trim()||void 0};return zi(t),t}function Xk(e){if(!(!e||e.length===0))return[...e].map(t=>({path:ur(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function O(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Zk(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=O(r.id),i=O(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=O(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function Qk(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=O(r.path);if(!o)continue;let i={path:ur(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=O(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function eE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=O(r.command),i=O(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=ur(i));let a=O(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function tE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=O(r.path);if(!o)continue;let i={path:ur(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=O(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function nE(e){if(e===null||typeof e!="object")return;let t=e,n=O(t.id),r=O(t.title),o=O(t.status),i=o&&uk.has(o)?o:void 0,s=ja(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let l={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return rE(l,t),l}function rE(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=O(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",Zk],["files","files",Qk],["tests","tests",eE],["docs","docs",tE]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function oE(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=nE(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function iE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=O(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=O(r.rationale);c&&(a.rationale=c);let l=O(r.evidence);l&&(a.evidence=l);let d=O(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function sE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=O(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=O(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function aE(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=O(r.text);if(!o)continue;let i={text:o},s=O(r.command);s&&(i.command=s);let a=O(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function cE(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function dr(e){let t=0;for(;t<e.length&&e[t]===`
|
|
4
|
+
`;)t+=1;return e.slice(t).trimEnd()}function lE(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Si.includes(t))return t}function dE(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ei.includes(t))return t}function Kr(e){return e||void 0}function uE(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Ka(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function fE(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=Mi(r,o,`metadata field "${r.metadata_key}"`))}}function pE(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Rf(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&Xt(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function Xr(e,t={}){let n=Of(t),r=Yt(e.status,n?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:wf(e.pm_format_version),source_type:O(e.source_type),type_options:cE(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Dk(e.dependencies),comments:za(e.comments),notes:za(e.notes),learnings:za(e.learnings),files:jk(e.files),tests:Gk(e.tests),test_runs:Uk(e.test_runs),docs:Xk(e.docs),deadline:Kr(e.deadline),reminders:Pk(e.reminders),events:Mk(e.events),closed_at:Kr(e.closed_at),completed_at:Kr(e.completed_at),assignee:O(e.assignee),claim_principal:O(e.claim_principal),source_owner:O(e.source_owner),author:Kr(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:O(e.definition_of_ready),order:e.order,goal:O(e.goal),objective:O(e.objective),value:O(e.value),impact:O(e.impact),outcome:O(e.outcome),why_now:O(e.why_now),parent:O(e.parent),reviewer:O(e.reviewer),risk:e.risk??void 0,confidence:lE(e.confidence),sprint:O(e.sprint),release:O(e.release),blocked_by:O(e.blocked_by),blocked_reason:O(e.blocked_reason),unblock_note:O(e.unblock_note),reporter:O(e.reporter),severity:dE(e.severity),environment:O(e.environment),repro_steps:O(e.repro_steps),resolution:O(e.resolution),expected_result:O(e.expected_result),actual_result:O(e.actual_result),affected_version:O(e.affected_version),fixed_version:O(e.fixed_version),component:O(e.component),regression:e.regression,customer_impact:O(e.customer_impact),close_reason:Kr(e.close_reason),plan_mode:O(e.plan_mode),plan_scope:O(e.plan_scope),plan_harness:O(e.plan_harness),plan_resume_context:O(e.plan_resume_context),plan_steps:oE(e.plan_steps),plan_decisions:iE(e.plan_decisions),plan_discoveries:sE(e.plan_discoveries),plan_validation:aE(e.plan_validation)};return uE(i,e),fE(i,n),pE(i,n),zi(i),i}function Nf(e){return Kt(e,Le)}function mE(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function _E(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=mE(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function gE(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
|
|
5
|
+
`,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function Va(e,t){return Xr(e,{...t,onWarning:void 0})}function hE(e,t,n={}){let r=gE(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=_E(r.content);o||(e.trimStart().startsWith("{")&&Jr("json_markdown","JSON front matter is not valid JSON"),Jr("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{Jr("json_markdown","JSON front matter is not valid JSON")}return Ga(s,t),{metadata:Va(s,n),body:dr(i)}}function yE(e,t,n={}){let r;try{r=Fa(e).value}catch{Jr("toon","TOON item document is not valid TOON")}D(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!Cf.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&Jr("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ga(o.front_matter,t),D(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Va(o.front_matter,n),body:dr(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return D(i===void 0||typeof i=="string","TOON item document body must be a string"),Ga(s,t),{metadata:Va(s,n),body:dr(typeof i=="string"?i:"")}}function wE(e,t={}){let n=Xr(e.metadata,t),r=Nf(n),o=JSON.stringify(r,null,2),i=dr(e.body??"");return i?`${o}
|
|
6
6
|
|
|
7
7
|
${i}
|
|
8
8
|
`:`${o}
|
|
9
|
-
`}function
|
|
10
|
-
`}function Ce(e,t={}){let n=Le(e);if(n)throw new h(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Jc(t);return r==="toon"?xh(e,o,t):Ah(e,o,t)}function Pt(e,t={}){return(t.format??"toon")==="toon"?Ih(e,t):Ch(e,t)}function we(e,t={}){return{metadata:Mn(e.metadata,t),body:on(e.body??"")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d71277c-e16c-56f4-a834-5200acfa6d7a")}catch{}})();import ud from"fast-json-patch";import{AsyncLocalStorage as Wy}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="624aced5-552c-5354-9e34-b96e267d34d1")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();import Br from"node:fs";import Lt from"node:path";import{fileURLToPath as Oh}from"node:url";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dffcc28d-16a3-53d4-ba02-5298ae7a6d63")}catch{}})();var Rh="@unbrained/pm-cli";function Nh(e){try{return JSON.parse(Br.readFileSync(e,"utf8")).name===Rh}catch{return!1}}function Dh(e){let t=Br.existsSync(e)&&Br.statSync(e).isDirectory()?Lt.resolve(e):Lt.dirname(Lt.resolve(e));for(;;){let n=Lt.join(t,"package.json");if(Br.existsSync(n)&&Nh(n))return t;let r=Lt.dirname(t);if(r===t)return;t=r}}function an(e,t=[]){let n=Oh(e),r=Dh(n);return r||Lt.resolve(Lt.dirname(n),...t)}import{readFileSync as ey,readdirSync as mN,statSync as ty}from"node:fs";import ee from"node:path";import $h from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="815165a9-27a7-5933-adae-c7e55330c8e4")}catch{}})();function pt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ph(e){let t=e.key.trim();if(t.length===0)return null;let n=pt(e.aliases),r=e.description?.trim();return{key:t,values:pt(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var Lh=e=>e,tl=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function Mh(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function Fh(e,t){let n=new Map;for(let r of e??[]){let o=Mh(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function el(e,t){return t?pt(e):void 0}function Mi(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Gr(e,t={}){let n=t.resolvePolicyCommand??Lh,r=e.name.trim();if(r.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=pt(e.aliases),l=(e.options??[]).map(u=>Ph(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=Fh(e.command_option_policies,n);return{name:r,description:Mi(e.description),default_status:Mi(e.default_status),folder:Mi(e.folder),aliases:c.length>0?c:void 0,required_create_fields:el(e.required_create_fields,o),required_create_repeatables:el(e.required_create_repeatables,i),options:s?l:void 0,command_option_policies:a?d:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88b2ed4e-b5fd-5014-abf1-c163db033abf")}catch{}})();var jh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],Uh=["dep","comment","note","learning","file","test","doc"],Fi=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],sN=["title","description","type","status","priority","tags","body",...Fi,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],aN=["title","description","body","status","closeReason","priority","type","tags",...Fi,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],rl={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},cN={...rl},lN={...rl},ol=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],il=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function sl(e){return Object.fromEntries(e)}var dN=sl([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...ol,["author","--author"],["message","--message"],["dep","--dep"],...il]),uN=sl([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...ol,...il,["author","--author"],["message","--message"],["force","--force"]]);function Hr(e){let t=zh(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function al(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=$h.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(o)||o==="."||o===".."||o.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return o}function zh(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function qh(e){return Gr(e,{resolvePolicyCommand:tl})}function Fn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Bh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:Fn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Fn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Gh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function Hh(e){if(Array.isArray(e.options))return e.options.map(t=>Bh(t)).filter(t=>t!==null)}function Vh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Gh(t)).filter(t=>t!==null)}function Wh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:n,description:o,default_status:i,folder:r,aliases:Fn(t,"aliases"),required_create_fields:Fn(t,"required_create_fields"),required_create_repeatables:Fn(t,"required_create_repeatables"),options:Hh(t),command_option_policies:Vh(t)}}function Kh(e,t){return e.required_create_fields?pt(e.required_create_fields):t?.required_create_fields??[]}function Yh(e,t){return e.required_create_repeatables?pt(e.required_create_repeatables):t?.required_create_repeatables??[]}function Xh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Jh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Zh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=al(e.folder??t?.folder??Hr(n)),s={name:n,folder:i,aliases:pt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Kh(e,t),required_create_repeatables:Yh(e,t),options:Xh(e,t),command_option_policies:Jh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function nl(e,t){for(let n of e){let r=qh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Zh(r,i))}}function Qh(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=Wh(o);i&&t.push(i)}}return t}function ue(e,t=null){let n=new Map;for(let c of wc)n.set(c.toLowerCase(),{name:c,folder:Ae[c],aliases:[],required_create_fields:[...jh],required_create_repeatables:[...Uh],options:[],command_option_policies:[]});nl(e.item_types?.definitions??[],n),nl(Qh(t),n);let r=[...n.values()].sort((c,l)=>c.name.localeCompare(l.name)),o={},i={},s={};for(let c of r){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let l of c.aliases)i[l.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,l)=>c.localeCompare(l));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c155ccd1-cf4c-57fd-9d0e-5274eb29a764")}catch{}})();var ny={json_markdown:".md",toon:".toon"},ry={".md":"json_markdown",".toon":"toon"};var cn=[".md",".toon"];function Vr(e){try{return ty(e),!0}catch{return!1}}function oy(e){try{let t=JSON.parse(ey(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function iy(e){let t=ee.resolve(e);for(;;){let n=ee.join(t,Xt),r=ee.join(n,Tr);if(Vr(r))return n;let o=ee.join(t,Tr);if(Vr(o)&&oy(o))return t;let i=ee.dirname(t);if(i===t)return;t=i}}function cl(e){return iy(e)??ee.resolve(e,Xt)}function re(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=ee.resolve(e,r);if(!Vr(ve(o))){let i=ee.join(o,Xt);if(Vr(ve(i)))return i}return o}return cl(e)}function Wr(e){let t=ee.resolve(e),n=ee.dirname(t);return ee.basename(t)==="pm"&&ee.basename(n)===".agents"?ee.dirname(n):t}function ve(e){return ee.join(e,Tr)}function sy(e,t,n=Ae){let r=n[t]??Hr(t);return ee.join(e,r)}function ln(e,t,n,r="toon",o=Ae){return ee.join(sy(e,t,o),`${n}${ny[r]}`)}function Kr(e){let t=e.replaceAll("\\","/"),n=ee.posix.extname(t).toLowerCase();return ry[n]??null}function Be(e,t){return ee.join(e,"history",`${t}.jsonl`)}function ll(e,t){return ee.join(e,"locks",`${t}.lock`)}function Yr(e){return ee.join(e,"runtime")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7dca67-8f1e-5451-b45c-4a75b1117d72")}catch{}})();var bN=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function Mt(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let l=s[0];for(let d=1;d<=t.length;d+=1){let u=e[c-1]===t[d-1]?0:1,f=i[d-1]+u,p=s[d-1]+1,_=i[d]+1,y=Math.min(f,p,_);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(y=Math.min(y,o[d-2]+1)),s[d]=y,y<l&&(l=y)}if(l>n)return null;for(let d=0;d<r;d+=1)o[d]=i[d],i[d]=s[d]}let a=i[t.length];return a<=n?a:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var dl=Zt;function $i(e){let t=e.trim().toLowerCase();return dl.includes(t)?t:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1558713a-91ea-5eef-8426-d910e0b77045")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function Ft(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ay(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function ul(e){return e?Ze(e):{}}function fl(e){return e?Ze(e):ay()}function Ze(e){return structuredClone(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="065f61c6-2123-5a6d-984a-569bb14d6911")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a30142c8-b04d-5878-8497-c902ff299e94")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dc9a3977-a78a-501e-b600-45e7031dcebd")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var pl=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="764d9a7d-90a2-578f-ab5d-bd0c039596df")}catch{}})();var LN=new Set(pl);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="057f439e-ac5c-5715-9fd0-4410e003d481")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ee7e43-8811-57ed-8bfe-0345ee5d3308")}catch{}})();var Ui=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),cy=new Set(Ui.flatMap(e=>[e.flag,...e.aliases??[]]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4eccf02f-7401-539f-b843-f55b63ed878c")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="849502d0-2616-500c-96de-228c0759459d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa7d04c7-b057-569c-816a-f53322c74261")}catch{}})();var zi=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7d44fba-603b-5ef2-8490-51112b929433")}catch{}})();function Xr(e){return e.trim().toLowerCase().replaceAll("-","_")}function ly(e){if(e===void 0)return;let t=Xr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function qi(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)qi(n,t);return Object.freeze(e)}for(let n of Object.values(e))qi(n,t);return Object.freeze(e)}function dy(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function uy(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function fy(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function py(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=Xr(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function my(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function _y(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function gy(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Bi=class{#e=new Map;#t=new Map;constructor(t=zi){for(let n of t)this.register(n)}register(t){let n=py(t);if(my(t,n),_y(t,n),dy(t,n),uy(t,n),fy(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=ly(t.inverse),o=[...new Set((t.aliases??[]).map(Xr))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#t.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:gy(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?qi(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#t.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Xr(t);return this.#e.get(this.#t.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function dn(){return new Bi}var VN=dn();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3225f4de-aa48-55b7-a704-d93ccb3ee0f4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24383c0a-592e-5105-84a3-a6cfb7801281")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48fff41d-2667-50a1-bfbb-40908804babd")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7c79f37-1cae-59c9-b500-eb87d0089f94")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49cea84c-1d1b-523b-8c98-7ac16c69ae82")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7316b9ef-38e1-5ee0-9107-da15ec7804d4")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1dd5d4f-5f08-5e52-b109-d066f92ae3b3")}catch{}})();var by=5e3;async function _l(e,t,n){let r=[];for(let o of e)try{await o.run(Ze(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function wy(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new h(`Extension mutation guard ${t.name} returned an invalid decision.`,g.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new h(`Extension mutation guard ${t.name} returned an invalid denial.`,g.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new h(s||`Extension mutation guard ${t.name} denied ${n}.`,g.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Gi(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:Ze(t.before),after:t.after===null?null:Ze(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new h(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},by),o.unref?.()})])}catch(i){throw i instanceof h?i:new h(`Extension mutation guard ${n.name} failed before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}wy(r,n,t.operation)}}async function Hi(e,t){return _l(e.onWrite,"onWrite",t)}async function Vi(e,t){return _l(e.onRead,"onRead",t)}function vy(e){return{handled:!1,result:e.payload,warnings:[]}}function Ey(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function ky(e){return{service:e.service,command:e.command?Ft(e.command):void 0,args:e.args?Ze(e.args):void 0,options:e.options?ul(e.options):void 0,global:e.global?fl(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:Ze(e.payload)}}function Ty(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function Sy(e,t){return Ty(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function Ay(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&xe(e,n.payload)}function xy(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}async function Wi(e,t){let n=Ey(e,t.service);if(n.length===0)return vy(t);let r=[];for(let o of n)try{let i=ky(t),s=await Promise.resolve(o.run(i));if(Ay(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=xy(o,Sy(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e4e1b7c2-6551-5e56-b26a-30062aed5b97")}catch{}})();var HD=Object.freeze(kr());(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9832a9-f6a2-5351-a929-0a0d2766df88")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3239b2c7-3ae3-5d4e-9005-b61000362304")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a35f3cdc-810e-59bd-8408-03ce792db57f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38024e6c-c1ef-5c15-8421-ac18d317e330")}catch{}})();var Jr=null;var Ky=null;var Yy=null,Xy=null;var Jy=[],Zy=new Wy;function mt(){return Zy.getStore()}var Qy=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Y(){let e=mt();return e?e.registrations:Yy}function Ki(e){if(!e)return;let t=mt();t?t.affectedItems.push(e):Jy.push(e)}function Zr(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||Qy.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function Ee(e){let t=mt(),n=t?t.hooks:Jr;return n?Hi(n,e):[]}async function Yi(e){let t=mt(),n=t?t.hooks:Jr;n&&await Gi(n,e)}async function Me(e){let t=mt(),n=t?t.hooks:Jr;return n?Vi(n,e):[]}function Qr(){let e=mt();return((e?e.hooks:Jr)?.onRead?.length??0)>0}function eb(e,t){let n=mt(),r=n?n.commandContext:Xy;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function Ge(e,t){let n=mt(),r=n?n.services:Ky;return r?Wi(r,eb(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as ns}from"node:async_hooks";import{createHash as lb}from"node:crypto";import He from"node:fs";import Sl from"node:os";import ro from"node:path";import{AsyncLocalStorage as tb}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="16109ee9-e684-5d25-a5f4-30a6c4f62bd5")}catch{}})();var nb=new tb,bl=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function eo(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function $n(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=eo(n.id,128),o=eo(n.parent_id,128);if(r===void 0||!bl.test(r)||o!==void 0&&!bl.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=eo(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Xi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=eo(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function rb(e,t,n){let r=nb.getStore(),o=Xi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=$n(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...Xi(r?.provenance),...o,...Xi(e?.provenance)},a=$n(e?.episode,!1)??$n(n,!1)??i??$n(r?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function to(e,t){return rb(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as Ji,promises as gP,readFileSync as ob}from"node:fs";import Qe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var ib="session.json";function Zi(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function sb(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Zi(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Zi(c,128)),a=t.focused_item_id===void 0||Zi(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function ab(e){return Qe.join(Yr(e),ib)}function cb(e,t){let n=t.PM_PATH?.trim();if(n){let o=Qe.resolve(e,n);if(Ji(Qe.join(o,"settings.json")))return o;let i=Qe.join(o,".agents","pm");if(Ji(Qe.join(i,"settings.json")))return i}let r=Qe.resolve(e);for(let o=0;o<32;o+=1){let i=Qe.join(r,".agents","pm");if(Ji(Qe.join(i,"settings.json")))return i;let s=Qe.dirname(r);if(s===r)break;r=s}}function wl(e){if(!e.key)return;let t=cb(e.cwd,e.env);if(t)try{let n=JSON.parse(ob(ab(t),"utf8"));return sb(n.semantic_attribution?.[e.key])}catch{return}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf550961-0040-5e04-9d8d-16e316027e43")}catch{}})();var rs=["model","effort","role","topic","version"],io=new ns,db=new ns,os=new ns,is=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Al=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),ub=Object.freeze({...Al,max_bytes:4194304}),Qi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function fb(e){let t=jn(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?ub:Al,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var pb=Object.freeze(is.filter(e=>e.harness!=="ci").map(fb).sort((e,t)=>e.harness.localeCompare(t.harness))),mb=new Map,_b=new Map;function V(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function $t(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function jn(e){let t=e.harness.trim().toLowerCase();if(!Qi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:$t(e.environment_keys),model_environment_keys:$t(e.model_environment_keys),session_environment_keys:$t(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),$t(r)]).filter(([n])=>Qi.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&Qi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:$t(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:$t(e.argv_markers).map(n=>n.toLowerCase()),client_names:$t(e.client_names).map(n=>n.toLowerCase())}}var gb=is.map(jn);function oo(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function xl(e=[]){let t=new Map(is.filter(o=>o.harness!=="ci").map(o=>[o.harness,jn(o)]));for(let{adapter:o}of mb.values())t.set(o.harness,jn(o.descriptor));let n=[...t.values(),...gb.filter(o=>o.harness==="ci"),...[..._b.values()].map(o=>o.descriptor),...os.getStore()?.descriptors??[],...e.map(jn)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function ss(e,t){for(let n of t??[]){let r=V(e[n]);if(r)return r.slice(0,256)}}function hb(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function Cl(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return V(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return V(i.slice(s.length+1))?.slice(0,256)}}var yb=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function jt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return yb.has(n)?n:void 0}function es(e,t){return V(e?.[t])?.slice(0,256)}var bb=1048576,vl=4194304,no=new Map,El=Object.freeze({}),ts=new Map,kl=Object.freeze({});function Tl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function wb(e){let t;try{t=JSON.parse(e)}catch{return kl}let n=Tl(t);if(!n)return kl;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=V(a.value.model)?.slice(0,256),s??=V(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=Tl(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function vb(e,t,n){let r=V(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=ro.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=ro.join(t.home_dir??Sl.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=He.openSync(s,"r");try{let c=He.fstatSync(a),l=`${s}\0${c.size}\0${c.mtimeMs}`,d=ts.get(l);if(d)return d[e];let u=Math.min(c.size,bb),f=Math.min(u,Math.ceil(u/2)),p=Math.min(u-f,c.size-f),_=Buffer.alloc(f);He.readSync(a,_,0,f,0);let y=Buffer.alloc(p);p>0&&He.readSync(a,y,0,p,c.size-p);let b={},E=c.size<=u?Buffer.concat([_,y]).toString("utf8").split(`
|
|
11
|
-
`):[...
|
|
12
|
-
`).slice(0,4096),...
|
|
13
|
-
`).slice(-4096)];for(let
|
|
14
|
-
`).reverse().slice(0,r);r-=s.length;for(let a of s)if(
|
|
9
|
+
`}function bE(e,t={}){let n=Xr(e.metadata,t),r=Nf(n),o=dr(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=ck(s),c;try{c=Fa(a).value}catch(l){throw new w("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:l instanceof Error?l.message:String(l)})}if(!Sf(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!Sf(s[u],l[u]))??"document";throw new w(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${d}".`,h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:d,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
|
|
10
|
+
`}function $e(e,t={}){let n=Me(e);if(n)throw new w(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Of(t);return r==="toon"?yE(e,o,t):hE(e,o,t)}function xn(e,t={}){return(t.format??"toon")==="toon"?bE(e,t):wE(e,t)}function Ke(e,t={}){return{metadata:Xr(e.metadata,t),body:dr(e.body??"")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d71277c-e16c-56f4-a834-5200acfa6d7a")}catch{}})();import s_ from"fast-json-patch";import{AsyncLocalStorage as Zx}from"node:async_hooks";import Pn from"node:fs/promises";import Dn from"node:path";import{pathToFileURL as ix}from"node:url";import Df from"path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="624aced5-552c-5354-9e34-b96e267d34d1")}catch{}})();function Zt(e,t){let n=Df.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!Df.isAbsolute(n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();var vE="__pm_suppress_host_output",Ja="@unbrained/pm-cli:suppress-host-output:v1";function Pf(e){return e===void 0?{__pm_suppress_host_output:Ja}:{__pm_suppress_host_output:Ja,result:e}}function Ya(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[vE]===Ja}import Hi from"node:fs";import Tn from"node:path";import{fileURLToPath as kE}from"node:url";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dffcc28d-16a3-53d4-ba02-5298ae7a6d63")}catch{}})();var EE="@unbrained/pm-cli";function SE(e){try{return JSON.parse(Hi.readFileSync(e,"utf8")).name===EE}catch{return!1}}function xE(e){let t=Hi.existsSync(e)&&Hi.statSync(e).isDirectory()?Tn.resolve(e):Tn.dirname(Tn.resolve(e));for(;;){let n=Tn.join(t,"package.json");if(Hi.existsSync(n)&&SE(n))return t;let r=Tn.dirname(t);if(r===t)return;t=r}}function Je(e,t=[]){let n=kE(e),r=xE(n);return r||Tn.resolve(Tn.dirname(n),...t)}import{readFileSync as VE,readdirSync as kz,statSync as WE}from"node:fs";import KE from"node:os";import ce from"node:path";import OE from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="815165a9-27a7-5933-adae-c7e55330c8e4")}catch{}})();function Qt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function TE(e){let t=e.key.trim();if(t.length===0)return null;let n=Qt(e.aliases),r=e.description?.trim();return{key:t,values:Qt(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var AE=e=>e,Mf=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function IE(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function CE(e,t){let n=new Map;for(let r of e??[]){let o=IE(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function Lf(e,t){return t?Qt(e):void 0}function Xa(e){let t=e?.trim();return t&&t.length>0?t:void 0}function qi(e,t={}){let n=t.resolvePolicyCommand??AE,r=e.name.trim();if(r.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Qt(e.aliases),l=(e.options??[]).map(u=>TE(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=CE(e.command_option_policies,n);return{name:r,description:Xa(e.description),default_status:Xa(e.default_status),folder:Xa(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Lf(e.required_create_fields,o),required_create_repeatables:Lf(e.required_create_repeatables,i),options:s?l:void 0,command_option_policies:a?d:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88b2ed4e-b5fd-5014-abf1-c163db033abf")}catch{}})();var RE=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],NE=["dep","comment","note","learning","file","test","doc"],Za=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],mz=["title","description","type","status","priority","tags","body",...Za,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],_z=["title","description","body","status","closeReason","priority","type","tags",...Za,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Ff={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},gz={...Ff},hz={...Ff},jf=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],Uf=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function zf(e){return Object.fromEntries(e)}var yz=zf([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...jf,["author","--author"],["message","--message"],["dep","--dep"],...Uf]),wz=zf([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...jf,...Uf,["author","--author"],["message","--message"],["force","--force"]]);function Qr(e){let t=DE(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Qa(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=OE.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(o)||o==="."||o===".."||o.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return o}function DE(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function PE(e){return qi(e,{resolvePolicyCommand:Mf})}function Zr(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function LE(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:Zr(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Zr(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function ME(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function $E(e){if(Array.isArray(e.options))return e.options.map(t=>LE(t)).filter(t=>t!==null)}function FE(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>ME(t)).filter(t=>t!==null)}function jE(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:n,description:o,default_status:i,folder:r,aliases:Zr(t,"aliases"),required_create_fields:Zr(t,"required_create_fields"),required_create_repeatables:Zr(t,"required_create_repeatables"),options:$E(t),command_option_policies:FE(t)}}function UE(e,t){return e.required_create_fields?Qt(e.required_create_fields):t?.required_create_fields??[]}function zE(e,t){return e.required_create_repeatables?Qt(e.required_create_repeatables):t?.required_create_repeatables??[]}function HE(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function qE(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function BE(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=Qa(e.folder??t?.folder??Qr(n)),s={name:n,folder:i,aliases:Qt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:UE(e,t),required_create_repeatables:zE(e,t),options:HE(e,t),command_option_policies:qE(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function $f(e,t){for(let n of e){let r=PE(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,BE(r,i))}}function GE(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=jE(o);i&&t.push(i)}}return t}function de(e,t=null){let n=new Map;for(let c of Xu)n.set(c.toLowerCase(),{name:c,folder:Oe[c],aliases:[],required_create_fields:[...RE],required_create_repeatables:[...NE],options:[],command_option_policies:[]});$f(e.item_types?.definitions??[],n),$f(GE(t),n);let r=[...n.values()].sort((c,l)=>c.name.localeCompare(l.name)),o={},i={},s={};for(let c of r){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let l of c.aliases)i[l.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,l)=>c.localeCompare(l));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c155ccd1-cf4c-57fd-9d0e-5274eb29a764")}catch{}})();var JE={json_markdown:".md",toon:".toon"},YE={".md":"json_markdown",".toon":"toon"};var Nt=[".md",".toon"];function Bi(e){try{return WE(e),!0}catch{return!1}}function XE(e){try{let t=JSON.parse(VE(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function ZE(e){let t=ce.resolve(e);for(;;){let n=ce.join(t,tr),r=ce.join(n,vi);if(Bi(r))return n;let o=ce.join(t,vi);if(Bi(o)&&XE(o))return t;let i=ce.dirname(t);if(i===t)return;t=i}}function Hf(e){return ZE(e)??ce.resolve(e,tr)}function te(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=ce.resolve(e,r);if(!Bi(be(o))){let i=ce.join(o,tr);if(Bi(be(i)))return i}return o}return Hf(e)}function en(e){let t=ce.resolve(e),n=ce.dirname(t);return ce.basename(t)==="pm"&&ce.basename(n)===".agents"?ce.dirname(n):t}function An(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:ce.join(KE.homedir(),".pm-cli");return ce.resolve(e,n)}function be(e){return ce.join(e,vi)}function QE(e,t,n=Oe){let r=n[t]??Qr(t);return ce.join(e,r)}function fr(e,t,n,r="toon",o=Oe){return ce.join(QE(e,t,o),`${n}${JE[r]}`)}function pr(e){let t=e.replaceAll("\\","/"),n=ce.posix.extname(t).toLowerCase();return YE[n]??null}function gt(e,t){return ce.join(e,"history",`${t}.jsonl`)}function qf(e,t){return ce.join(e,"locks",`${t}.lock`)}function Gi(e){return ce.join(e,"runtime")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7dca67-8f1e-5451-b45c-4a75b1117d72")}catch{}})();var eS=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function ec(e){return typeof e!="string"?null:eS[e.trim().toLowerCase()]??null}function tc(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function Bf(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function ht(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let l=s[0];for(let d=1;d<=t.length;d+=1){let u=e[c-1]===t[d-1]?0:1,f=i[d-1]+u,p=s[d-1]+1,m=i[d]+1,g=Math.min(f,p,m);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(g=Math.min(g,o[d-2]+1)),s[d]=g,g<l&&(l=g)}if(l>n)return null;for(let d=0;d<r;d+=1)o[d]=i[d],i[d]=s[d]}let a=i[t.length];return a<=n?a:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var Vi=Wt;function Wi(e){let t=e.trim().toLowerCase();return Vi.includes(t)?t:null}function Gf(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Vi)if(ht(t,r,n)!==null)return r;return null}import tS from"node:fs/promises";import eo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}catch{}})();async function Vf(e,t){let n=eo.dirname(t.manifest_path),r=eo.relative(n,t.entry_path);if(r.startsWith("..")||eo.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=eo.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await tS.cp(n,o,{recursive:!0,force:!0}),eo.join(o,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1558713a-91ea-5eef-8426-d910e0b77045")}catch{}})();function Wf(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([n,r])=>[n,r.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[n,r]of Object.entries(t.registrations))e.registrations[n].length=r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function pe(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function nS(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function Kf(e){return e?ot(e):{}}function Jf(e){return e?ot(e):nS()}function ot(e){return structuredClone(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="065f61c6-2123-5a6d-984a-569bb14d6911")}catch{}})();function Yf(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return pe(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function Xf(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a30142c8-b04d-5878-8497-c902ff299e94")}catch{}})();function Zf(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dc9a3977-a78a-501e-b600-45e7031dcebd")}catch{}})();function ve(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function Te(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function ue(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function Qf(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function In(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function to(e,t){if(In(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var nc=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="764d9a7d-90a2-578f-ab5d-bd0c039596df")}catch{}})();var rS=new Set(nc);function oS(e){if(e!==void 0&&!rS.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${nc.join(", ")}`)}function ep(e){ue("registerCommand definition.action",e.action),ue("registerCommand definition.family",e.family),ue("registerCommand definition.description",e.description),ue("registerCommand definition.intent",e.intent),ue("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");oS(e.family)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="057f439e-ac5c-5715-9fd0-4410e003d481")}catch{}})();function iS(e){let t=ve("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return ue("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function tp(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=iS(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function rc(e,t,n){return{registration:t,action:n,command:e.command,args:ot(e.args),options:ot(e.options),global:ot(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ee7e43-8811-57ed-8bfe-0345ee5d3308")}catch{}})();var oc=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),ic=new Set(oc.flatMap(e=>[e.flag,...e.aliases??[]]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4eccf02f-7401-539f-b843-f55b63ed878c")}catch{}})();var sS=/^--[a-z0-9][a-z0-9_-]*(?:[ =](?:<[^<>]+>|\[[^[\]]+\]))?$/;function aS(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return ic.has(n)?"host_owned_flag_collision":sS.test(t)?null:"malformed_long_flag"}function np(e,t){let n=[e,t].find(i=>typeof i=="string"&&ic.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=aS(r);return o===null?null:{token:r,failure:o}}function rp(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="849502d0-2616-500c-96de-228c0759459d")}catch{}})();function op(e){return typeof e=="string"?e:String(e)}function no(e){let n=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(n)?n.split(/[.-]/).map(r=>Number(r)):null}function sc(e,t){let n=no(e),r=no(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function ip(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=op(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!no(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=sc(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function sp(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=op(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!no(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=sc(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,current:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa7d04c7-b057-569c-816a-f53322c74261")}catch{}})();var ac=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7d44fba-603b-5ef2-8490-51112b929433")}catch{}})();function Ki(e){return e.trim().toLowerCase().replaceAll("-","_")}function cS(e){if(e===void 0)return;let t=Ki(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function cc(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)cc(n,t);return Object.freeze(e)}for(let n of Object.values(e))cc(n,t);return Object.freeze(e)}function lS(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function dS(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function uS(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function fS(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=Ki(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function pS(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function mS(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function _S(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var lc=class{#e=new Map;#n=new Map;constructor(t=ac){for(let n of t)this.register(n)}register(t){let n=fS(t);if(pS(t,n),mS(t,n),lS(t,n),dS(t,n),uS(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=cS(t.inverse),o=[...new Set((t.aliases??[]).map(Ki))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:_S(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?cc(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Ki(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Cn(){return new lc}var tH=Cn();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3225f4de-aa48-55b7-a704-d93ccb3ee0f4")}catch{}})();function ro(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function On(e){return Ve.includes(e)}function ap(e){return e.filter(t=>!On(t))}function dc(e){let t=e.trim().toLowerCase();return t.length===0?null:xa[t]??null}function cp(e){let t=ro([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=dc(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:ro(n),legacy_aliases:o}}function gS(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=dc(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of Ve){let a=ht(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function lp(e,t,n){let r=Ve.join(","),o=gS(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function dp(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function uc(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(p=>p.trim()).filter(p=>p.length>0),l=dc(o),u=(s==="none"?void 0:s)??l??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:mi,suggested_capability:u,suggestion_source:u?l===u?"legacy_alias":"nearest_match":void 0,legacy_alias_target:l??void 0}}function fc(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...Ve],a=[];for(let c of o.split(",")){let[l,d]=c.split(">"),u=l?.trim(),f=d?.trim().toLowerCase();!u||!f||!On(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:mi,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24383c0a-592e-5105-84a3-a6cfb7801281")}catch{}})();function it(e){return typeof e!="string"?"":e.trim().toLowerCase()}function B(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function hS(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function mr(e){return new Set((e??[]).map(t=>hS(t)).filter(t=>t.length>0))}function up(e){let t=it(e);return gi.includes(t)?t:"off"}function fp(e){let t=it(e);return hi.includes(t)?t:"off"}function oo(e){let t=it(e);return yi.includes(t)?t:"none"}function pc(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Ku.includes(t)?t:void 0}function pp(e){if(typeof e=="string"){let t=pc(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:pc(e.global)??"block",project:pc(e.project)??"block"}:{global:"block",project:"block"}}function yS(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function J(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function wS(e){let t=it(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?oo(e.sandbox_profile):void 0,allowedCapabilities:B(e.allowed_capabilities),blockedCapabilities:B(e.blocked_capabilities),allowedSurfaces:mr(e.allowed_surfaces),blockedSurfaces:mr(e.blocked_surfaces),allowedCommands:B(e.allowed_commands),blockedCommands:B(e.blocked_commands),allowedActions:B(e.allowed_actions),blockedActions:B(e.blocked_actions),allowedServices:B(e.allowed_services),blockedServices:B(e.blocked_services)}}}function mp(e){let t=new Map;for(let n of e??[]){let r=wS(n);r&&t.set(r.name,r.normalized)}return t}function bS(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of J([...e.allowedCapabilities,...e.blockedCapabilities]))On(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of J([...o.allowedCapabilities,...o.blockedCapabilities]))On(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(wi);for(let o of J([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of J([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function _p(e){let t=e.extensions?.policy??{},n=B(t.allowed_capabilities),r=B(t.blocked_capabilities),o=mr(t.allowed_surfaces),i=mr(t.blocked_surfaces),s=mp(t.extension_overrides);return{mode:up(t.mode),trustMode:fp(t.trust_mode),pmMaxVersionExceededMode:pp(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:B(t.trusted_extensions),defaultSandboxProfile:oo(t.default_sandbox_profile),allowedExtensions:B(t.allowed_extensions),blockedExtensions:B(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:B(t.allowed_commands),blockedCommands:B(t.blocked_commands),allowedActions:B(t.allowed_actions),blockedActions:B(t.blocked_actions),allowedServices:B(t.allowed_services),blockedServices:B(t.blocked_services),overridesByName:s,warnings:bS({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function gp(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:J(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:J(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:J(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:J(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:J(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:J(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:J(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:J(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:J(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:J(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:yS(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:J(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:J(e.allowedExtensions),blocked_extensions:J(e.blockedExtensions),allowed_capabilities:J(e.allowedCapabilities),blocked_capabilities:J(e.blockedCapabilities),allowed_surfaces:J(e.allowedSurfaces),blocked_surfaces:J(e.blockedSurfaces),allowed_commands:J(e.allowedCommands),blocked_commands:J(e.blockedCommands),allowed_actions:J(e.allowedActions),blocked_actions:J(e.blockedActions),allowed_services:J(e.allowedServices),blocked_services:J(e.blockedServices),extension_overrides:t}}function hp(e){let t=mp(e.extension_overrides);return{mode:up(e.mode),trustMode:fp(e.trust_mode),pmMaxVersionExceededMode:pp(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:B(e.trusted_extensions),defaultSandboxProfile:oo(e.default_sandbox_profile),allowedExtensions:B(e.allowed_extensions),blockedExtensions:B(e.blocked_extensions),allowedCapabilities:B(e.allowed_capabilities),blockedCapabilities:B(e.blocked_capabilities),allowedSurfaces:mr(e.allowed_surfaces),blockedSurfaces:mr(e.blocked_surfaces),allowedCommands:B(e.allowed_commands),blockedCommands:B(e.blocked_commands),allowedActions:B(e.allowed_actions),blockedActions:B(e.blocked_actions),allowedServices:B(e.allowed_services),blockedServices:B(e.blocked_services),overridesByName:t,warnings:[]}}function tn(e,t){return e.overridesByName.get(it(t))??null}function _r(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function yp(e,t,n){let r=n.trim().toLowerCase(),o=tn(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return _r(i,s,r,"capability_not_allowlisted","capability_blocked")}function vS(e,t,n){let r=tn(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return _r(o,i,n,"surface_not_allowlisted","surface_blocked")}function kS(e,t,n){let r=pe(n);if(r.length===0)return null;let o=tn(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return _r(i,s,r,"command_not_allowlisted","command_blocked")}function ES(e,t,n){let r=it(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=tn(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return _r(i,s,r,"action_not_allowlisted","action_blocked")}function SS(e,t,n){let r=it(n);if(r.length===0)return null;let o=tn(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return _r(i,s,r,"service_not_allowlisted","service_blocked")}function xS(e,t){let n=it(t.name);return tn(e,t.name)?.disabled===!0?"extension_override_disabled":_r(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function TS(e,t){if(e.trustMode==="off")return null;let n=tn(e,t.name),r=it(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function AS(e,t){if(e.mode==="off")return null;let r=tn(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(r==="none")return null;let o=t.permissions;if(!o)return"sandbox_permissions_missing";let i=s=>o[s]===!0;return r==="restricted"?i("process_spawn")?"sandbox_restricted_disallows_process_spawn":i("env_write")?"sandbox_restricted_disallows_env_write":null:i("process_spawn")?"sandbox_strict_disallows_process_spawn":i("network")?"sandbox_strict_disallows_network":i("fs_write")?"sandbox_strict_disallows_fs_write":i("env_write")?"sandbox_strict_disallows_env_write":null}function Ji(e,t,n,r,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${n.layer}:${n.name}:reason=${r}${s}`}function wp(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=xS(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=TS(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=AS(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:Ji("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:Ji("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function bp(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=yp(e,t,n);return r?{allowed:e.mode==="warn",warning:Ji(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function IS(e,t,n,r,o){let i=typeof r=="string"?yp(e,t,r):null,s=vS(e,t,n),a=o.command?kS(e,t,o.command):null,c=o.action?ES(e,t,o.action):null,l=o.service?SS(e,t,o.service):null;return i??s??a??c??l}function CS(e,t,n,r){let o={method:it(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=pe(r.command)),r.action&&(o.action=it(r.action).replace(/\s+/g,"-")),r.service&&(o.service=it(r.service)),o}function vp(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=IS(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=Ji(e.mode==="warn"?"violation":"blocked","registration",t,a,CS(r,n,o,s));return{allowed:e.mode==="warn",warning:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48fff41d-2667-50a1-bfbb-40908804babd")}catch{}})();function Yi(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function mc(){return{overrides:[],handlers:[]}}function _c(){return{overrides:[]}}function gc(){return{overrides:[]}}function hc(){return{overrides:[]}}function yc(){return{overrides:[]}}function Xi(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7c79f37-1cae-59c9-b500-eb87d0089f94")}catch{}})();var OS=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),RS=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function NS(e,t){for(let n of RS){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>OS.has(n)?pe(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function DS(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>pe(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function PS(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>pe(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function io(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let n={schema_version:1};if(!NS(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=DS(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=PS(i);if(s===null)return null;n.preflight_ownership=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49cea84c-1d1b-523b-8c98-7ac16c69ae82")}catch{}})();var LS=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function MS(e){return{unknownKeys:Object.keys(e).filter(t=>!LS.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function wc(e){let t=MS(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function kp(e,t,n){return wc(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7316b9ef-38e1-5ee0-9107-da15ec7804d4")}catch{}})();function Ep(e){return e==="toon"||e==="json"}function Sp(e){return er.includes(e)}function Rn(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var xp=Symbol("extension_registration_trace");function Dt(e,t){let n=new TypeError(e);return Object.defineProperty(n,xp,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function Tp(e){return e instanceof Error?e[xp]:void 0}function so(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>so(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=so(t[r]);return n}return e}function ao(e){if(Array.isArray(e))return e.map(t=>ao(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=ao(t[r]);return n}return e}function gr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return so(t)}function co(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return ao(t)}function Zi(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>gr(e,n))}function Fe(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function lo(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function bc(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function vc(e,t){return pe(`${e} ${t}`)}function uo(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var $S=new Set(["low","medium","high"]),FS=new Set(["number","string_set"]),jS=new Set(["string","number","boolean"]);function Ap(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function US(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=ve(r,n);if(!FS.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(ue(`${r}.description`,o.description),o.parameters===void 0)return;let i=ve(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;Ap(`${c}.name`,s);let l=ve(c,a);if(!jS.has(String(l.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);Te(`${c}.required`,l.required),ue(`${c}.description`,l.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function Ip(e){let t=ve("registerAssuranceMeasurementProvider provider",e),n=Ap("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!$S.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=ve("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);US(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();function Cp(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1dd5d4f-5f08-5e52-b109-d066f92ae3b3")}catch{}})();var zS=5e3;async function Op(e,t,n){let r=[];for(let o of e)try{await o.run(ot(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function HS(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new w(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new w(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new w(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function kc(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:ot(t.before),after:t.after===null?null:ot(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new w(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},zS),o.unref?.()})])}catch(i){throw i instanceof w?i:new w(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}HS(r,n,t.operation)}}async function Ec(e,t){return Op(e.onWrite,"onWrite",t)}async function Sc(e,t){return Op(e.onRead,"onRead",t)}function qS(e){return{handled:!1,result:e.payload,warnings:[]}}function BS(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function GS(e){return{service:e.service,command:e.command?pe(e.command):void 0,args:e.args?ot(e.args):void 0,options:e.options?Kf(e.options):void 0,global:e.global?Jf(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:ot(e.payload)}}function VS(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function WS(e,t){return VS(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function KS(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&rt(e,n.payload)}function JS(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}async function xc(e,t){let n=BS(e,t.service);if(n.length===0)return qS(t);let r=[];for(let o of n)try{let i=GS(t),s=await Promise.resolve(o.run(i));if(KS(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=JS(o,WS(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e4e1b7c2-6551-5e56-b26a-30062aed5b97")}catch{}})();var zp=100,Rp=null,sx=Object.freeze(bi()),Np=0;function Hp(e=Date.now()){return Np+=1,`${Np}-${e}`}function Dp(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function ax(e){if(e==null)return;let t=Sn(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Tc(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function qp(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function Nn(e){if(e!=null)return typeof e!="boolean"?null:e}function cx(e){let t=qp(e.priority);return t===void 0?zp:t}function lx(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=oo(t);return n!==t.trim().toLowerCase()?null:n}function Ac(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function dx(e){if(e==null)return;let t=Sn(e);if(!t)return null;let n=Ac(t.source),r=Ac(t.signature),o=Ac(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function ux(e){if(e==null)return;let t=Sn(e);if(!t)return null;let n=Nn(t.fs_read),r=Nn(t.fs_write),o=Nn(t.network),i=Nn(t.env_read),s=Nn(t.env_write),a=Nn(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function fx(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=cp(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function px(e){if(e==null)return;let t=Sn(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>pe(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function mx(e){let t=qp(e.manifest_version);if(t===null)return null;let n=Dp(e,"pm_min_version");if(n===null)return null;let r=Dp(e,"pm_max_version");if(r===null)return null;let o=ax(e.engines);if(o===null)return null;let i=Nn(e.trusted);if(i===null)return null;let s=lx(e);if(s===null)return null;let a=dx(e.provenance);if(a===null)return null;let c=ux(e.permissions);if(c===null)return null;let l=fx(e.capabilities);if(l===null)return null;let d=px(e.activation);if(d===null)return null;let u=io(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:l.capabilities,legacy_capability_aliases:l.legacy_aliases,activation:d,contributions:u}}function Bp(e){if(typeof e!="object"||e===null)return null;let t=e,n=Tc(t,"name");if(n===null)return null;let r=Tc(t,"version");if(r===null)return null;let o=Tc(t,"entry");if(o===null)return null;let i=cx(t);if(i===null)return null;let s=mx(t);return s===null?null:{name:n,version:r,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}function _x(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function Gp(e,t){let[n,r]=await Promise.all([Pn.realpath(e),Pn.realpath(t)]);return Zt(n,r)}function Qi(e,t=process.cwd()){return{global:Dn.join(An(t),"extensions"),project:Dn.join(e,"extensions")}}async function gx(e){try{return(await Pn.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort((n,r)=>n.localeCompare(r))}catch{return[]}}function hx(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function Pp(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function yx(e){let t=new Map;try{let n=JSON.parse(await Pn.readFile(Dn.join(e,".managed-extensions.json"),"utf8")),o=Sn(n)?.entries;if(!Array.isArray(o))return t;for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=Pp(s.source?.package),c=[s.source?.input,s.source?.name,a].map(u=>Pp(u)).filter(u=>u!==void 0),l=io(s.contributions),d={aliases:[...new Set(c)],...a?{package_name:a}:{},...l?{contributions:l}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&t.set(`directory:${s.directory.trim()}`,d),typeof s.name=="string"&&s.name.trim().length>0&&t.set(`name:${s.name.trim()}`,d)}}catch{return t}return t}function Lp(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function wx(e,t){let n=[...Lp(e),...Lp(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Mp(e,t,n,r,o){let i=[],s=[],a=[],c=await gx(t),l=await yx(t);for(let d of c){let u=await kx(e,t,d,n,r,l,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function bx(){return{diagnostics:[],warnings:[],candidates:[]}}function $p(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function vx(e,t,n,r,o,i,s){let a=kp(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&a.push(dp(e,t.name,t.legacy_capability_aliases));for(let c of ap(t.capabilities))a.push(lp(e,t.name,c));return r?o||a.push(`extension_entry_missing:${e}:${t.name}`):a.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&a.push(i.warning),s.warning&&a.push(s.warning),a}async function kx(e,t,n,r,o,i,s){let a=Dn.join(t,n),c=Dn.join(a,"manifest.json");if(!await U(c))return $p(e,n,c,`extension_manifest_missing:${e}:${n}`);let l,d;try{let x=JSON.parse(await Pn.readFile(c,"utf8"));d=Sn(x),l=Bp(x)}catch{d=null,l=null}if(!l||!d)return $p(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=Dn.resolve(a,l.entry),f=Zt(a,u),p=f?await U(u):!1,m=f&&p?await Gp(a,u):f,g=_x(l.name,r,o),y=await Sx(e,l),b=await xx(e,l,s),v=vx(e,l,d,m,p,y,b),A=m&&p&&y.allowed&&b.allowed,I=i.get(`directory:${n}`)??i.get(`name:${l.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:l.name,version:l.version,entry:l.entry,priority:l.priority,entry_path:u,enabled:g,status:A?"ok":"warn"},warnings:v,candidate:Cp({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:l,sourceIdentity:I,extensionReady:A,enabledForLoad:g})}}async function Vp(e){let t=Qi(e.pmRoot,e.cwd??process.cwd()),n=ro(e.settings.extensions.enabled),r=ro(e.settings.extensions.disabled),o=_p(e.settings),i=gp(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?bx():await Mp("global",t.global,s,a,o.pmMaxVersionExceededMode.global),l=await Mp("project",t.project,s,a,o.pmMaxVersionExceededMode.project),d=[...o.warnings],u=wx(c.candidates,l.candidates),f=[];for(let p of u){let m={layer:p.layer,name:p.manifest.name,trusted:p.manifest.trusted===!0,provenanceVerified:p.manifest.provenance?.verified===!0,sandboxProfile:p.manifest.sandbox_profile,permissions:p.manifest.permissions&&typeof p.manifest.permissions=="object"?{fs_read:p.manifest.permissions.fs_read,fs_write:p.manifest.permissions.fs_write,network:p.manifest.permissions.network,env_read:p.manifest.permissions.env_read,env_write:p.manifest.permissions.env_write,process_spawn:p.manifest.permissions.process_spawn}:void 0},g=wp(o,m);if(g.warning&&d.push(g.warning),!!g.allowed){for(let y of p.manifest.capabilities){let b=bp(o,m,y);b.warning&&d.push(b.warning)}f.push(hx(p))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...l.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...l.warnings,...d])],policy:i}}function Rc(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function Ex(){try{let e=Je(import.meta.url,["../../.."]),t=await Pn.readFile(Dn.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Wp(){return Rp??=Ex(),Rp}function Kp(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function Sx(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=ip(t.pm_min_version,await Wp()),r=Kp(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function xx(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=sp(t.pm_max_version,await Wp(),n),o=Kp(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Fp(e){try{let t=await Pn.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function Tx(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Vf(t.module_graph_snapshot_root,e));let r=new URL(ix(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[i,s]=await Promise.all([Fp(e.entry_path),Fp(e.manifest_path)]),a=t.reload_token??Hp();return r.searchParams.set("pm_ext_reload",a),r.searchParams.set("pm_ext_entry",i),r.searchParams.set("pm_ext_manifest",s),r.href}async function fo(e){let t=await Vp(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let c=await import(await Tx(s,e));n.push({...s,module:c})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:Rc(a)})}return{...t,warnings:o,loaded:n,failed:r}}function Ax(e){let n={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let r=e.deactivate;n.deactivate=r.bind(e)}return n}function Ix(e){let t=Ef(e);return t?Ax(t):null}var Cx=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","visible"]);function Ic(e,t){return Zi(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function Ox(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function jp(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let n=Ox(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Up(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[r,o]of e.entries()){let i=ve(`registerCommand definition.arguments[${r}]`,o),s=Fe(`registerCommand definition.arguments[${r}].name`,i.name);if(Te(`registerCommand definition.arguments[${r}].required`,i.required),Te(`registerCommand definition.arguments[${r}].variadic`,i.variadic),ue(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function Cc(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=ve(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!Cx.has(c)).sort((c,l)=>c.localeCompare(l));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);ue(`registerFlags flags[${t}].long`,i),ue(`registerFlags flags[${t}].short`,s);let a=np(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${rp(a.token,a.failure)}`);if(ue(`registerFlags flags[${t}].value_name`,r.value_name),ue(`registerFlags flags[${t}].description`,r.description),Te(`registerFlags flags[${t}].required`,r.required),Te(`registerFlags flags[${t}].enabled`,r.enabled),Te(`registerFlags flags[${t}].visible`,r.visible),Te(`registerFlags flags[${t}].list`,r.list),Te(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Qf(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Rx(`registerFlags flags[${t}]`,r)}}function Rx(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=ec(n);if(r===null)throw new TypeError(`${e} value_type "${n}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?tc(t.default):[t.default];for(let[i,s]of o.entries())if(!Bf(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Nx(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=ve(`registerItemFields fields[${t}]`,n);Fe(`registerItemFields fields[${t}].name`,r.name);let o=Fe(`registerItemFields fields[${t}].type`,r.type);if(Wi(o)===null){let i=Gf(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Vi.join(", ")}).${s}`)}Te(`registerItemFields fields[${t}].optional`,r.optional)}}function Dx(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=ve(i,o);Fe(`${i}.command`,s.command),Fe(`${i}.option`,s.option),Te(`${i}.enabled`,s.enabled),Te(`${i}.required`,s.required),Te(`${i}.visible`,s.visible)}}function Px(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=ve(i,o);Fe(`${i}.key`,s.key),In(`${i}.values`,s.values),Te(`${i}.required`,s.required),In(`${i}.aliases`,s.aliases)}}function Lx(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=ve(r,n);Fe(`${r}.name`,o.name),ue(`${r}.folder`,o.folder),In(`${r}.aliases`,o.aliases),In(`${r}.required_create_fields`,o.required_create_fields),In(`${r}.required_create_repeatables`,o.required_create_repeatables),Dx(t,o.command_option_policies),Px(t,o.options)}}function Mx(e){let t=ve("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(Te("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var Jp=["types","statuses","fields","workflows","config","templates","packages"],$x={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Fx(e){let t=ve("registerProfile profile",e);if(Fe("registerProfile profile.name",t.name),Fe("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let n of Jp){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);$x[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function jx(e){e.summary===void 0&&(e.summary="");for(let t of Jp)e[t]===void 0&&(e[t]=[]);return e}function Ux(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();On(r)&&t.add(r)}return t}function re(e,t,n){let r=Ux(e);if(r!==null&&!r.has(t))throw Dt(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${n} registration call.`})}function zx(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>Ve.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function Hx(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var Oc=class{extension;hooks;#e;#n;#r;#o;#s;#a;#c;#l;#t;#i;#d;#u;constructor(t,n,r,o,i,s,a,c,l,d,u){this.#e=t,this.extension=zx(t),this.#n=Hx(t),this.#r=n,this.#o=r,this.#s=o,this.#a=i,this.#c=s,this.#l=a,this.#t=c,this.#i=l,this.#d=d,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=vp(this.#u,this.#n,t,n,r,o);return i.warning&&this.#i.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#o.overrides.length:this.#o.handlers.length,command:n,expected_schema:r,received:so(o),hint:i}}registerCommandOverride(t,n){let r=pe(t);if(r.length===0)throw Dt("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Dt(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#o.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#i.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Dt("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Dt("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=pe(t.name);if(n.length===0)throw Dt("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Dt(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{ep(t);let o=jp(n,t.action);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let i=t.description?.trim(),s=t.intent?.trim(),a=to("registerCommand definition.examples",t.examples),c=to("registerCommand definition.failure_hints",t.failure_hints),l=Up(t.arguments);t.flags!==void 0&&(re(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(Cc(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Ic("registerCommand definition.flags",t.flags)})));let d={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:a,failure_hints:c,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};i&&(d.description=i),s&&(d.intent=s),this.#t.commands.push(d)}catch(o){let i=Rc(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Dt(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#i.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#d.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#o.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(re(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(re(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=pe(Fe("registerParser command",t));lo("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(re(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Yf(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){re(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!Sp(o))throw new TypeError(`registerService service must be one of: ${er.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(lo("registerService override",n),this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...Zf(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(re(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!Ep(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return pe(s)}))];this.#l.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(re(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=pe(Fe("registerFlags targetCommand",t));Cc(n);let o=Ic("registerFlags flags",n);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:o})}registerItemFields(t){if(re(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Nx(t);let n=Zi("registerItemFields fields",t);if(n.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:n})}registerItemTypes(t){if(re(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Lx(t);let n=Zi("registerItemTypes types",t);if(n.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:n})}registerRelationshipKinds(t){if(re(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let n=Cn();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(re(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Mx(t);let n=co("registerMigration definition",t);this.#t.migrations.push(uo({layer:this.#e.layer,name:this.#e.name,definition:gr("registerMigration definition",t)},n))}registerProfile(t){if(re(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=ao(t);Fx(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:jx(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(re(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(Cc(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Ic(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...r,description:r?.description??o,arguments:r?.arguments??i},a=tp(t,s,r?.description!==void 0);ue(`${t} options.action`,s.action),ue(`${t} options.description`,s.description),ue(`${t} options.intent`,s.intent);let c=jp(n,s.action),l=to(`${t} options.examples`,s.examples),d=to(`${t} options.failure_hints`,s.failure_hints),u=Up(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:l,failure_hints:d,arguments:u},p=s.description?.trim();p&&(f.description=p);let m=s.intent?.trim();return m&&(f.intent=m),this.#t.commands.push(f),a}registerImporter(t,n,r){if(re(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=bc(Fe("registerImporter name",t));lo("registerImporter importer",n);let i=vc(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#o.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n(rc(s,o,"import"))})}registerExporter(t,n,r){if(re(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=bc(Fe("registerExporter name",t));lo("registerExporter exporter",n);let i=vc(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#o.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(rc(a,o,"export"));return s?.receipt==="suppress"&&!Ya(c)?Pf(c):c}})}registerSearchProvider(t){if(re(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=co("registerSearchProvider provider",t);this.#t.search_providers.push(uo({layer:this.#e.layer,name:this.#e.name,definition:gr("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(re(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=co("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(uo({layer:this.#e.layer,name:this.#e.name,definition:gr("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(re(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(Ip(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=co("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(uo({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:gr("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){re(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(Rn("beforeCommand",t),this.#r.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){re(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(Rn("beforeMutation",t),this.#r.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){re(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(Rn("afterCommand",t),this.#r.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){re(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(Rn("onWrite",t),this.#r.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){re(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(Rn("onRead",t),this.#r.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){re(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(Rn("onIndex",t),this.#r.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function qx(e,t,n,r,o,i,s,a,c,l,d){return new Oc(e,t,n,r,o,i,s,a,c,l,d)}function Bx(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:n,item_fields:r,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function Gx(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let l=a.get(c.command)??[];l.push(c),a.set(c.command,l)}for(let c of[...a.keys()].sort((l,d)=>l.localeCompare(d))){let l=a.get(c);if(l.length<=1)continue;let d=l[l.length-1];for(let u of l.slice(0,-1))t.push(`${s}:${c}:${d.layer}:${d.name}:${u.layer}:${u.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let l of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${l.layer}:${l.name}`)}return t}function Vx(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Wx(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Kx=new Set(["output_format"]);function Jx(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Kx.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function po(e){let t=hp(e.policy??sx),n=Yi(),r=mc(),o=_c(),i=gc(),s=hc(),a=yc(),c=Xi(),l=[],d=[];for(let p of e.loaded){let m=Ix(p.module);if(!m)continue;let g=l.length,y=Wf({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await m.activate(qx(p,n,r,o,i,s,a,c,d,l,t)),l.length>g&&(y(),d.push(`extension_activation_rolled_back:${p.layer}:${p.name}`))}catch(b){y(),d.push(`extension_activate_failed:${p.layer}:${p.name}`);let v=Tp(b);l.push({layer:p.layer,name:p.name,entry_path:p.entry_path,error:Rc(b),trace:v})}}let u=[...Gx(r),...Wx(o),...Xf(i),...Jx(s),...Vx(a)],f=[...new Set([...d,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:l,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:Bx(c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9832a9-f6a2-5351-a929-0a0d2766df88")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3239b2c7-3ae3-5d4e-9005-b61000362304")}catch{}})();function es(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.push(o))}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a35f3cdc-810e-59bd-8408-03ce792db57f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38024e6c-c1ef-5c15-8421-ac18d317e330")}catch{}})();var ts=null;var Qx=null;var eT=null,tT=null;var nT=[],rT=new Zx;function nn(){return rT.getStore()}var oT=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function K(){let e=nn();return e?e.registrations:eT}function Nc(e){if(!e)return;let t=nn();t?t.affectedItems.push(e):nT.push(e)}function ns(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||oT.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function je(e){let t=nn(),n=t?t.hooks:ts;return n?Ec(n,e):[]}async function Dc(e){let t=nn(),n=t?t.hooks:ts;n&&await kc(n,e)}async function Ue(e){let t=nn(),n=t?t.hooks:ts;return n?Sc(n,e):[]}function rs(){let e=nn();return((e?e.hooks:ts)?.onRead?.length??0)>0}function iT(e,t){let n=nn(),r=n?n.commandContext:tT;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function yt(e,t){let n=nn(),r=n?n.services:Qx;return r?xc(r,iT(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as Uc}from"node:async_hooks";import{createHash as mT}from"node:crypto";import ze from"node:fs";import nm from"node:os";import $n from"node:path";import{AsyncLocalStorage as sT}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="16109ee9-e684-5d25-a5f4-30a6c4f62bd5")}catch{}})();var aT=new sT,Yp=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function os(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function mo(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=os(n.id,128),o=os(n.parent_id,128);if(r===void 0||!Yp.test(r)||o!==void 0&&!Yp.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=os(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Pc(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=os(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function cT(e,t,n){let r=aT.getStore(),o=Pc({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=mo(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...Pc(r?.provenance),...o,...Pc(e?.provenance)},a=mo(e?.episode,!1)??mo(n,!1)??i??mo(r?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function is(e,t){return cT(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as Lc,promises as Eq,readFileSync as lT}from"node:fs";import Pt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var dT="session.json";function Mc(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function uT(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Mc(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Mc(c,128)),a=t.focused_item_id===void 0||Mc(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function fT(e){return Pt.join(Gi(e),dT)}function pT(e,t){let n=t.PM_PATH?.trim();if(n){let o=Pt.resolve(e,n);if(Lc(Pt.join(o,"settings.json")))return o;let i=Pt.join(o,".agents","pm");if(Lc(Pt.join(i,"settings.json")))return i}let r=Pt.resolve(e);for(let o=0;o<32;o+=1){let i=Pt.join(r,".agents","pm");if(Lc(Pt.join(i,"settings.json")))return i;let s=Pt.dirname(r);if(s===r)break;r=s}}function Xp(e){if(!e.key)return;let t=pT(e.cwd,e.env);if(t)try{let n=JSON.parse(lT(fT(t),"utf8"));return uT(n.semantic_attribution?.[e.key])}catch{return}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfbf4eb8-1f02-5880-a70a-0e7ed9b9784a")}catch{}})();var zc=["model","effort","role","topic","version"],cs=new Uc,_T=new Uc,Hc=new Uc,qc=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],rm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),gT=Object.freeze({...rm,max_bytes:4194304}),$c=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function hT(e){let t=_o(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?gT:rm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var yT=Object.freeze(qc.filter(e=>e.harness!=="ci").map(hT).sort((e,t)=>e.harness.localeCompare(t.harness))),wT=new Map,bT=new Map;function se(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Ln(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function _o(e){let t=e.harness.trim().toLowerCase();if(!$c.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Ln(e.environment_keys),model_environment_keys:Ln(e.model_environment_keys),session_environment_keys:Ln(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),Ln(r)]).filter(([n])=>$c.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&$c.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Ln(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Ln(e.argv_markers).map(n=>n.toLowerCase()),client_names:Ln(e.client_names).map(n=>n.toLowerCase())}}var vT=qc.map(_o);function as(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function om(e=[]){let t=new Map(qc.filter(o=>o.harness!=="ci").map(o=>[o.harness,_o(o)]));for(let{adapter:o}of wT.values())t.set(o.harness,_o(o.descriptor));let n=[...t.values(),...vT.filter(o=>o.harness==="ci"),...[...bT.values()].map(o=>o.descriptor),...Hc.getStore()?.descriptors??[],...e.map(_o)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function Bc(e,t){for(let n of t??[]){let r=se(e[n]);if(r)return r.slice(0,256)}}function kT(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function im(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return se(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return se(i.slice(s.length+1))?.slice(0,256)}}var ET=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Mn(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return ET.has(n)?n:void 0}function Fc(e,t){return se(e?.[t])?.slice(0,256)}var ST=1048576,Zp=4194304,ss=new Map,Qp=Object.freeze({}),jc=new Map,em=Object.freeze({});function tm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function xT(e){let t;try{t=JSON.parse(e)}catch{return em}let n=tm(t);if(!n)return em;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=se(a.value.model)?.slice(0,256),s??=se(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=tm(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function sm(e){try{return ze.lstatSync(e).isFile()?"available":"missing"}catch(t){return ut(t)?"missing":"failed"}}function TT(e,t){let n;try{n=ze.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=$n.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:sm(i)}})}catch(o){return{status:ut(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function am(e,t){let n=se(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let o=$n.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),i=$n.join(e.home_dir??nm.homedir(),".claude","projects"),s=$n.join(i,o,`${n}.jsonl`),a=se(e.session_file),c=a&&$n.basename(a)===`${n}.jsonl`?a:void 0;for(let l of[c,s]){if(!l)continue;let d=sm(l);if(d==="available")return{status:d,path:l};if(d==="failed")return{status:d}}return TT(i,n)}function AT(e,t,n){let r=am(t,n);if(r.status==="available")try{let o=ze.openSync(r.path,ze.constants.O_RDONLY|ze.constants.O_NOFOLLOW);try{let i=ze.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=jc.get(s);if(a)return a[e];let c=Math.min(i.size,ST),l=Math.min(c,Math.ceil(c/2)),d=Math.min(c-l,i.size-l),u=Buffer.alloc(l);ze.readSync(o,u,0,l,0);let f=Buffer.alloc(d);d>0&&ze.readSync(o,f,0,d,i.size-d);let p={},m=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
|
|
11
|
+
`):[...u.toString("utf8").split(`
|
|
12
|
+
`).slice(0,4096),...f.toString("utf8").split(`
|
|
13
|
+
`).slice(-4096)];for(let y of m){if(y.length===0||y.length>262144)continue;let b=xT(y);if(p.model??=b.model,p.version??=b.version,p.model&&p.version)break}let g=Object.freeze(p);return jc.clear(),jc.set(s,g),g[e]}finally{ze.closeSync(o)}}catch{return}}function IT(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=ze.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=$n.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let l=r(c,i+1);if(l)return l}}};return r(e,0)}function CT(e){if(e<=Zp)return[{offset:0,length:e}];let t=Math.floor(Zp/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function OT(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=se(o?.model)?.slice(0,256),e.effort??=se(o?.effort)?.slice(0,256)}function RT(e,t){let n={},r=4096;for(let o of CT(t)){let i=Buffer.alloc(o.length);ze.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
|
|
14
|
+
`).reverse().slice(0,r);r-=s.length;for(let a of s)if(OT(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function NT(e,t,n){let r=se(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=$n.join(t.home_dir??nm.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=ss.get(i);if(s)return s[e];let a=IT(o,r);if(!a){ss.set(i,Qp);return}try{let c=ze.openSync(a,"r");try{let l=ze.fstatSync(c).size,d=RT(c,l);return ss.set(i,d),d[e]}finally{ze.closeSync(c)}}catch{ss.set(i,Qp);return}}function DT(e,t,n,r){let o=Hc.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(se(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return AT(e,t,n);if(s==="codex_session_file")return NT(e,t,n);if(s==="ai_agent_version"){let a=se(n.AI_AGENT);return!a||!r||!as(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function PT(e,t,n,r){if(e==="ai_agent_version"){let o=se(r.AI_AGENT);return o!==void 0&&as(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?se(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":am(n,r).status}function Gc(e){return e||(_T.getStore()??{env:process.env,argv:process.argv})}function LT(e,t,n,r){let o=e.environment_keys.some(a=>se(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return as(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||as(r,a));return o||i||s}function MT(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function $T(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function FT(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...zc,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=Mn(e,se(n[s])?.slice(0,256)),d=Mn(e,im(t.argv??[],e)),l=Mn(e,kT(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},p=Fc(o?.provenance,e),m=Mn(e,Bc(n,u[e])),g=Mn(e,Fc(f,e)),y=Mn(e,Fc(t.provenance,e)),b=DT(e,t,n,r);return $T([[c,"override"],[p,"session"],[d,"argv"],[m,"environment"],[g,"mcp_client"],[y,"host"],[b,"probe"]])??MT(e,i)??(l?{value:l,source:"argv"}:void 0)}function jT(e,t){if(!(!e||!t))return mT("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function UT(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...zc,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let l=FT(c,e,t,n,r,o);l?a[c]=l:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function Vc(e){let t=Gc(e),n=t.env??{},r=om(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(m=>m.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(m=>LT(m,n,o,i)),a=is(t,n),c=[Bc(n,s?.session_environment_keys),se(t.client_info?.session)?.slice(0,256)].find(m=>m!==void 0),l=jT(s?.harness,c),d=Xp({cwd:t.cwd??process.cwd(),env:n,key:l}),u=UT(t,n,s,a,d),f=u.model,p=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",l],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(p.filter(m=>m[1]!==void 0))}function zT(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function HT(e,t,n,r,o,i,s){let a=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=PT(a,n,r,o);return{...zT(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function Wc(e){let t=Gc(e),n=Vc(t),r=om(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Hc.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(se(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=is(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,Bc(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,im(t.argv??[],"role")].some(l=>{let d=se(l)?.slice(0,256);return d!==void 0&&Mn("role",d)===void 0}),c=Object.fromEntries(zc.map(l=>[l,HT(l,n,r,t,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function qT(e,t,n){let r=Gc(n),o=Vc(r);if(e!==void 0){let s=se(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=se(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=se(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function cm(e){let t=cs.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function lm(e){let t=cs.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function Kc(e){let t=cs.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Ye(e,t){let n=qT(e,t);return cs.enterWith(n),n.author}import wt from"node:fs/promises";import $t from"node:path";import{randomUUID as _A}from"node:crypto";import{createRequire as gA}from"node:module";import{constants as BT}from"node:fs";import st from"node:fs/promises";import ds from"node:path";import{randomUUID as Jc}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b21a63b8-9da9-5c7c-b288-3a2dae342bef")}catch{}})();function GT(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c},warnings:[]}}async function ls(e,t=!0){try{let n=await st.readFile(e,"utf8");return t&&await Ue({path:e,scope:"project"}),GT(n)}catch(n){return j(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Lt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function VT(e,t,n=process.platform){if(Lt(e,"EEXIST"))return!0;if(!Lt(e,"EPERM")&&!Lt(e,"EACCES")&&!Lt(e,"EBUSY"))return!1;try{return await st.lstat(t),!0}catch(r){if(n!=="win32"||!j(r)&&!Lt(r,"EPERM")&&!Lt(r,"EACCES")&&!Lt(r,"EBUSY"))return!1}try{return await st.access(ds.dirname(t),BT.W_OK),!0}catch{return!1}}async function _m(e,t){await je({path:e,scope:"project",op:t})}function WT(e,t,n,r=Jc()){return{id:e,pid:process.pid,owner:t,token:r,created_at:F(),ttl_seconds:n}}async function KT(e,t,n,r,o){await st.mkdir(ds.dirname(e),{recursive:!0});let i=await st.open(e,"wx");try{await i.writeFile(`${JSON.stringify(WT(t,n,r,o),null,2)}
|
|
15
|
+
`,"utf8")}finally{await i.close()}await _m(e,"lock:create")}async function gm(e,t){try{return await st.unlink(e),await _m(e,t),!0}catch{return!1}}async function JT(e,t,n,r){let o=Date.now(),i=ym;for(;;){let s=await Tm(e,t);if(s!==null){try{let l=await ls(e,!1);dm(l.info,t,n,r)&&await gm(e,"lock:release")}finally{await s()}return}let a=await ls(e,!1);if(!dm(a.info,t,n,r))return;let c=Date.now()-o;if(c>=um)return;await vm(Math.min(i,um-c)),i=Math.min(i*2,Yc)}}function dm(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function hm(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}function YT(e){return e?.owner?` (owner ${e.owner})`:""}var ym=25,Yc=200,XT=250,ZT=3,QT=".stale-cleanup",wm="owner.json",bm=1e4,um=bm+Yc,eA=60*6e4;function fm(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function tA(e){let t=process.env.PM_LOCK_WAIT_MS,n=fm(t);if(n!==void 0)return n;let r=fm(e);return r!==void 0?r:0}function vm(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function km(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new w(`Item ${e} is locked${YT(t)}${r}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:XT}})}function nA(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function rA(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new w(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function oA(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,...typeof i=="string"?{process_start_identity:i}:{}}}async function Em(e){try{return oA(await st.readFile(ds.join(e,wm),"utf8"))}catch{return null}}function iA(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!Lt(t,"ESRCH")}}function sA(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function Sm(e){try{return sA(await st.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function Xc(e=process.pid){let t=await Sm(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function xm(e,t,n){if(!iA(e.pid))return!1;let r=await Sm(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function Zc(e){try{return await st.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function pm(e,t){let n=await Em(e);n===null||n.token!==t||await Zc(e)}async function mm(e){try{await st.mkdir(e)}catch(n){return Lt(n,"EEXIST"),null}let t={...await Xc(),token:Jc()};try{await st.writeFile(ds.join(e,wm),`${JSON.stringify(t)}
|
|
16
|
+
`,"utf8")}catch{return await Zc(e),null}return t}async function aA(e){let t;try{let r=await st.stat(e);if(t=Date.now()-r.mtimeMs,t<=bm)return!1}catch(r){return j(r)}let n=await Em(e);return n!==null&&await xm(n,t,eA)?!1:Zc(e)}async function Tm(e,t){let n=`${e}${QT}`,r=await mm(n);if(r!==null)return async()=>pm(n,r.token);if(!await aA(n))return null;let o=await mm(n);return o===null?null:async()=>pm(n,o.token)}async function cA(e){let t=await Tm(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await ls(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!hm(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(rA(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=ZT)throw km(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await gm(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function ke(e,t,n,r,o=!1,i=!0,s){let a=await yt("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let m=nA(a.result);if(m)return async()=>{await Promise.resolve(m()),await yt("lock_release",{pm_root:e,id:t,owner:r})}}let c=qf(e,t),l=tA(s),d=Date.now(),u=0,f=ym,p=Jc();for(;;)try{return await KT(c,t,r,n,p),async()=>{await JT(c,t,r,p),await yt("lock_release",{pm_root:e,id:t,owner:r})}}catch(m){if(!await VT(m,c))throw new w(`Failed to acquire lock for ${t}: ${ne(m)}`,h.GENERIC_FAILURE);let g=await ls(c);if(hm(g.info,n)){let b=await cA({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:u,waitBudgetMs:l,startedAtMs:d,fallbackLockInfo:g});if(g=b.lockInfo,b.staleRemovalCounted&&(u+=1),b.shouldRetryCreate)continue}let y=Date.now()-d;if(l===0||y>=l)throw km(t,g.info,l===0?0:y);await vm(Math.min(f,l-y)),f=Math.min(f*2,Yc)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function Mt(e,t){let n=await Z(e);if(n===null)return[];if(await Ue({path:e,scope:"project"}),n.trim()==="")return[];let r=Me(n);if(r)throw new w(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let o=[];for(let[i,s]of n.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new w(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE)}}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6398c65d-fb5c-5479-93c2-0be963352a92")}catch{}})();var lA=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","normalize","release","test_run_track","tests_add","tests_remove","update_audit","update_ownership_bypass"],dA=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],uA=new Set(lA),fA=new Set(dA),pA=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function mA(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function Fn(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:uA.has(e.op)?"maintenance":fA.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=mA(t);return n!==void 0&&pA.has(n)})?"maintenance":"substantive"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="72b285a7-970e-5965-bacf-a4e0cfc5f060")}catch{}})();var hA="history-event-index.sqlite",yA="5";var wA="history-event-index",Qc=300,Am=3e4,bA="history-event-index-invalidation",vA="history-event-index-invalidations",pB=Qc*2*1e3;function el(e){return $t.join(e,"runtime",hA)}function kA(e){return $t.join(e,"runtime",vA)}async function EA(e,t){let n=await ke(e,bA,Qc,`history-event-index-invalidation:${process.pid}`,!1,!1,Am);try{return await t()}finally{await n()}}async function SA(e){let t=kA(e);await wt.mkdir(t,{recursive:!0});let n=_A(),r=await Xc(),o=$t.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await wt.writeFile(o,`pending
|
|
17
|
+
`,{flag:"wx"}),{pendingPath:o,committedPath:$t.join(t,`${n}.committed`)}}async function us(e){try{await wt.rm(el(e),{force:!0})}catch{}}async function xA(e,t){let n=await ke(e,wA,Qc,`history-event-index:${process.pid}`,!1,!1,Am);try{return await t()}finally{await n()}}function TA(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function AA(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?TA(t):null}var fs;function IA(){return fs!==void 0||(fs=AA(process.versions.node,gA(import.meta.url))),fs}function CA(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
|
|
15
18
|
stream_id, stream_offset, ts, author, agent_harness,
|
|
16
|
-
agent_instance, op, entry_json
|
|
17
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,t.entry.ts,t.entry.author,t.entry.agent_harness??null,t.entry.agent_instance??null,t.entry.op,JSON.stringify(t.entry))}async function Nl(e,t){let n=un.dirname(un.dirname(e)),r=Rl(n);try{await us.access(r)}catch{return}let o=qb();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==jb)throw new TypeError("Unsupported history event index version");let a=un.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);Bb(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await us.rm(r,{force:!0})}}async function ao(e){await us.rm(Rl(un.dirname(un.dirname(e))),{force:!0})}import hs from"node:fs/promises";import fn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();import{AsyncLocalStorage as Cw}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();function Dl(e,t,n){if(e&&t)throw new h(`${n} cannot be combined with --full`,g.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var Gb=1,Hb=4096;var KP=Object.freeze({version:Gb,max_length:Hb});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="810d42b5-98f4-57a7-bdd9-2dfa1b2b1c03")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02a0bd0c-6ab0-5193-807b-00394a4712b7")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9694bd-3635-5298-abeb-6899c94317ab")}catch{}})();var co=[...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],Kb=Object.fromEntries(co.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6315a62f-6f55-5200-a5ea-ec892ff39f58")}catch{}})();var Yb=[...Tn],Xb=[...Er],Jb=[...di],Zb=[...ui],Qb=[...fi],ew=[...pi],lo=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"];var Pl=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Ll=["upgrade"],Ml=["reopen"],Fl={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},gt=Object.freeze(lo.flatMap(e=>e in Fl?[]:e==="extension"||e==="package"?[...Pl.map(t=>`${e}-${t}`),...e==="package"?Ll.map(t=>`package-${t}`):[],e]:e==="item"?Ml.map(t=>`item-${t}`):[e])),$l=Object.freeze(co.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&>.includes(e.alias)).map(e=>e.alias)),tw=Object.freeze(gt.filter(e=>!$l.includes(e)));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d338971-5a60-5b4e-b4c8-0705c8e8c98c")}catch{}})();var jl=["full","compact","brief","summary","counts"];var Ul=["error","warning","validation_summary","recovery_bundle"],zl=["full","omit_explanation","limit_collections","compact_recovery","action_only"],nw=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),rw=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),ow=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),iw={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},sw=3,aw=2,cw=192,lw={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},ql=Ul.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:lw[e],minimum_max_estimated_tokens:cw,degradation_ladder:zl,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),oL=new Map(ql.map(e=>[e.diagnostic_class,e]));function Bl(e){let[t=""]=e.trim().split(/\s+/u);return nw.has(t)?"mutation":rw.has(t)?"discovery":ow.has(t)?"governance":"read"}function Gl(e,t=Bl(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=iw[t];return Hl({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*sw/aw)},degradation_ladder:jl,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Hl(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var Vl=lo.map(e=>Gl(e)),iL=new Map(Vl.map(e=>[e.command,e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var uw=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),fw=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:uw}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="642f6dec-c0b2-5377-a401-dfa4f8ef6a2a")}catch{}})();var Wl=256,uo=1e4,mw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,_w=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var yL=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&mw.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Wl,reason:`token_budget must be a safe integer of at least ${Wl}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=uo&&e.seen_item_ids.every(t=>typeof t=="string"&&_w.test(t)),reason:`seen_item_ids must contain at most ${uo} portable item identifiers.`}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2103a4dc-3037-5768-b2c7-5964de4ac86b")}catch{}})();var Kl=["include","amount","cost","encoding"],Yl=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"],Ew=["canonical","legacy","intent","default"],fs={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Xl=Object.freeze(Kl.map(e=>fs[e])),Jl=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Zl={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},Ql=new Set(["--collapse","--fields","--section"]),ps=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function ed(e){return e.slice(2).replaceAll("-","_")}function kw(e,t){let n=ps[e];if(n!==void 0)return n;let r=t==="include"?Ql.has(e)?"<csv>":ed(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${fs[t]} ${r}.`}function Tw(e){let t=Zl[e],n=Object.freeze(Object.fromEntries(Kl.map(r=>[r,Object.freeze({dimension:r,canonical_option:fs[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:ps[o]===void 0?"replacement":"behavior_preserving",migration_hint:kw(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Ew,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...Aw(e).keys()])})}var Sw=Object.freeze(Yl.map(Tw)),UL=new Map(Sw.map(e=>[e.command,e]));function Un(e,t={}){let n=e.trim().toLowerCase().replaceAll(/\s+/gu," "),o=n==="package catalog"||n==="packages catalog"||n==="package-catalog"||(n==="package"||n==="packages"||n==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":n==="package manage"||n==="package-manage"?"package-manage":n.split(" ")[0],i=o.startsWith("list-")?"list":o==="ctx"?"context":o;return Yl.includes(i)?i:void 0}function Aw(e){let t=Un(e);return t?new Map((Zl[t].include??[]).filter(n=>!Ql.has(n)&&ps[n]===void 0).map(n=>[ed(n),xw(n)])):new Map}function xw(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="da15ca02-02cc-5886-8c82-610939b8581c")}catch{}})();var tM=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),nM=new Cw;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();import{encode as kM}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="202cbb3e-71fe-5701-a1f5-eb515bf56561")}catch{}})();var TM=new Set(Object.values(g));var td=!1;function ms(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Ow(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function Rw(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function _s(e){if(e==="stdout"){Ow();return}Rw()}function nd(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function Nw(){td||(td=!0,process.stdout.on("error",e=>{if(ms(e)){_s("stdout");return}nd(e)}),process.stderr.on("error",e=>{if(ms(e)){_s("stderr");return}nd(e)}))}function Dw(e,t){Nw();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(ms(n))return _s(e),!1;throw n}}function gs(e){return Dw("stderr",e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var Pw=fn.join("runtime","history-drift-cache.json"),od={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function id(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function ys(e){let t=fn.join(e,Pw),n=!1,r="invalid_cache_path";try{n=(await hs.stat(await hs.realpath(e))).isDirectory()}catch(o){let i=id(o);r=i===void 0?"unknown":od[i]??"filesystem_error"}if(!n){gs(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
18
|
-
`);return}try{await hs.rm(t,{force:!0})}catch(o){let i=id(o);if(H(o))return;let s=i===void 0?"unknown":od[i]??"filesystem_error";gs(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
19
|
-
`)
|
|
19
|
+
agent_instance, op, event_class, entry_json
|
|
20
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,Fn(n),JSON.stringify(n))}function OA(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
|
|
21
|
+
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(t,n)}async function Im(e,t,n){let r=$t.dirname($t.dirname(e)),o=IA();if(!o){await n();return}let i=!1;try{await xA(r,async()=>{let s=el(r);try{await wt.access(s)}catch{await n();return}let a;try{if(a=new o(s),a.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==yA)throw new TypeError("Unsupported history event index version")}catch{a?.close(),await wt.rm(s,{force:!0}),await n();return}try{a.exec("PRAGMA busy_timeout = 5000"),a.exec("BEGIN IMMEDIATE")}catch(l){throw a.close(),l}let c=!1;try{await n(),c=!0,i=!0;let l=$t.basename(e,".jsonl"),d=a.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);CA(a,{stream_id:l,stream_offset:Number(d.value),entry:t}),OA(a,l,(await wt.stat(e)).size),a.exec("COMMIT"),a.close()}catch(l){if(a?.close(),!c)throw l;await us(r)}})}catch(s){if(i){await us(r);return}if(!(s instanceof w)||s.code!=="lock_conflict")throw s;let a;try{await EA(r,async()=>{let c=await SA(r);a=c.pendingPath;try{await n(),i=!0}catch(l){throw await wt.rm(c.pendingPath,{force:!0}),l}await wt.rename(c.pendingPath,c.committedPath),await us(r)})}catch(c){if(i){await us(r);try{await wt.rm(a,{force:!0})}catch{}return}throw c}}}async function tl(e){await wt.rm(el($t.dirname($t.dirname(e))),{force:!0})}import cl from"node:fs/promises";import yr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();import{AsyncLocalStorage as gI}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();function Cm(e,t,n){if(e&&t)throw new w(`${n} cannot be combined with --full`,h.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var RA=1,NA=4096;var EB=Object.freeze({version:RA,max_length:NA});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="810d42b5-98f4-57a7-bdd9-2dfa1b2b1c03")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02a0bd0c-6ab0-5193-807b-00394a4712b7")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9694bd-3635-5298-abeb-6899c94317ab")}catch{}})();var ps=[...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],nl=Object.fromEntries(ps.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6315a62f-6f55-5200-a5ea-ec892ff39f58")}catch{}})();var LA=[...Ve],MA=[...er],$A=[...gi],FA=[...hi],jA=[...yi],UA=[...wi],hr=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"];var Om=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Rm=["upgrade"],Nm=["reopen"],Dm={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},rn=Object.freeze(hr.flatMap(e=>e in Dm?[]:e==="extension"||e==="package"?[...Om.map(t=>`${e}-${t}`),...e==="package"?Rm.map(t=>`package-${t}`):[],e]:e==="item"?Nm.map(t=>`item-${t}`):[e])),Pm=Object.freeze(ps.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&rn.includes(e.alias)).map(e=>e.alias)),zA=Object.freeze(rn.filter(e=>!Pm.includes(e)));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1d338971-5a60-5b4e-b4c8-0705c8e8c98c")}catch{}})();var Lm=["full","compact","brief","summary","counts"];var Mm=["error","warning","validation_summary","recovery_bundle"],$m=["full","omit_explanation","limit_collections","compact_recovery","action_only"],HA=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),qA=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),BA=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),GA={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},VA=3,WA=2,KA=192,JA={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Fm=Mm.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:JA[e],minimum_max_estimated_tokens:KA,degradation_ladder:$m,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),DB=new Map(Fm.map(e=>[e.diagnostic_class,e]));function jm(e){let[t=""]=e.trim().split(/\s+/u);return HA.has(t)?"mutation":qA.has(t)?"discovery":BA.has(t)?"governance":"read"}function Um(e,t=jm(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=GA[t];return zm({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*VA/WA)},degradation_ladder:Lm,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function zm(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var Hm=hr.map(e=>Um(e)),PB=new Map(Hm.map(e=>[e.command,e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var XA=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),ZA=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:XA}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="642f6dec-c0b2-5377-a401-dfa4f8ef6a2a")}catch{}})();var qm=256,ms=1e4,eI=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,tI=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var WB=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&eI.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=qm,reason:`token_budget must be a safe integer of at least ${qm}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=ms&&e.seen_item_ids.every(t=>typeof t=="string"&&tI.test(t)),reason:`seen_item_ids must contain at most ${ms} portable item identifiers.`}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2103a4dc-3037-5768-b2c7-5964de4ac86b")}catch{}})();var Bm=["include","amount","cost","encoding"],Gm=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"],cI=["canonical","legacy","intent","default"],rl={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Vm=Object.freeze(Bm.map(e=>rl[e])),Wm=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Km={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},Jm=new Set(["--collapse","--fields","--section"]),ol=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function Ym(e){return e.slice(2).replaceAll("-","_")}function lI(e,t){let n=ol[e];if(n!==void 0)return n;let r=t==="include"?Jm.has(e)?"<csv>":Ym(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${rl[t]} ${r}.`}function dI(e){let t=Km[e],n=Object.freeze(Object.fromEntries(Bm.map(r=>[r,Object.freeze({dimension:r,canonical_option:rl[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:ol[o]===void 0?"replacement":"behavior_preserving",migration_hint:lI(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:cI,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...fI(e).keys()])})}var uI=Object.freeze(Gm.map(dI)),_G=new Map(uI.map(e=>[e.command,e]));function go(e,t={}){let n=e.trim().toLowerCase().replaceAll(/\s+/gu," "),o=n==="package catalog"||n==="packages catalog"||n==="package-catalog"||(n==="package"||n==="packages"||n==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":n==="package manage"||n==="package-manage"?"package-manage":n.split(" ")[0],i=o.startsWith("list-")?"list":o==="ctx"?"context":o;return Gm.includes(i)?i:void 0}function fI(e){let t=go(e);return t?new Map((Km[t].include??[]).filter(n=>!Jm.has(n)&&ol[n]===void 0).map(n=>[Ym(n),pI(n)])):new Map}function pI(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="997a09a2-cf0c-5384-b457-d9627d465b71")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5dc9c6e4-6db8-560f-a87f-368132e2ffb3")}catch{}})();var NG=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),DG=new gI;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();import{encode as t2}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa89762b-915f-5ef0-a091-f05338c11683")}catch{}})();var n2=new Set(Object.values(h));var Xm=!1;function il(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function yI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function wI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function sl(e){if(e==="stdout"){yI();return}wI()}function Zm(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function bI(){Xm||(Xm=!0,process.stdout.on("error",e=>{if(il(e)){sl("stdout");return}Zm(e)}),process.stderr.on("error",e=>{if(il(e)){sl("stderr");return}Zm(e)}))}function vI(e,t){bI();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(il(n))return sl(e),!1;throw n}}function al(e){return vI("stderr",e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var kI=yr.join("runtime","history-drift-cache.json"),e_={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function t_(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function ll(e){let t=yr.join(e,kI),n=!1,r="invalid_cache_path";try{n=(await cl.stat(await cl.realpath(e))).isDirectory()}catch(o){let i=t_(o);r=i===void 0?"unknown":e_[i]??"filesystem_error"}if(!n){al(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
22
|
+
`);return}try{await cl.rm(t,{force:!0})}catch(o){let i=t_(o);if(j(o))return;let s=i===void 0?"unknown":e_[i]??"filesystem_error";al(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
23
|
+
`)}}async function on(e){let t=yr.dirname(yr.resolve(e));yr.basename(t)==="history"&&await ll(yr.dirname(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf6a9831-134c-5dc2-a3e2-74dca00cf22c")}catch{}})();var bt=3,at=[1,2,3],a_=1,c_=[1];function fl(e){return ye(N(e))}function jn(e){return ye(N(e))}function br(e){let t={...e,record_hash_version:a_},{record_hash:n,...r}=t;return{...t,record_hash:fl(r)}}function an(e){if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!c_.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return fl(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function EI(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:jn(e.patch)};return e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function vr(e,t,n={}){let r=an(e);if(!r.ok)throw new TypeError(r.error);let o=jn(e.patch),i=n.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||o!==jn(t.patch),s=br({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],EI(e,n)]}:{}}),a=hs(s);if(!a.ok)throw new TypeError(a.error);return s}function l_(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!wr(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function SI(e){return wr(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&l_(e.patch)}function xI(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function TI(e){return!wr(e)||!xI(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!l_(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.record_hash))?!1:e.record===void 0||SI(e.record)}function AI(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&jn(t.patch)===e.patch_hash}function II(e,t,n){if(t.patch&&jn(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return AI(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(jn(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...n.length===0?{}:{reanchor_evidence:n}};return n.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function hs(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r];if(!(r in t)||!TI(o))return{ok:!1,error:"rewrite_evidence_invalid"};let i=II(n,o,t.slice(0,r));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!an(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function _s(e,t){return(e??"").localeCompare(t??"")}function n_(e,t){return(e??0)-(t??0)}function sn(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function CI(e,t){return[e.scope.localeCompare(t.scope),_s(e.path,t.path),_s(e.command,t.command),n_(e.timeout_seconds,t.timeout_seconds),_s(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,sn(e.env_clear,t.env_clear,[]),sn(e.env_set,t.env_set,{}),sn(e.assert_stdout_contains,t.assert_stdout_contains,[]),sn(e.assert_stdout_regex,t.assert_stdout_regex,[]),sn(e.assert_stderr_contains,t.assert_stderr_contains,[]),sn(e.assert_stderr_regex,t.assert_stderr_regex,[]),n_(e.assert_stdout_min_lines,t.assert_stdout_min_lines),sn(e.assert_json_field_equals,t.assert_json_field_equals,{}),sn(e.assert_json_field_gte,t.assert_json_field_gte,{}),_s(e.note,t.note)].find(r=>r!==0)??0}function OI(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function RI(e,t){let n=OI(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:wr(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function NI(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!RI(r,o.path)?{...o,op:"add"}:o;n.push(i),r=s_.applyPatch(r,[i],!0,!0).newDocument}return n}function gs(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let o=Ke(e),s=t===1||t===2&&n?{...o.metadata,...o.metadata.dependencies===void 0?{}:{dependencies:o.metadata.dependencies.map(l=>({...l,id:l.id.toLowerCase()}))},...o.metadata.tests===void 0?{}:{tests:o.metadata.tests.map(({workspace_context_mode:l,provenance:d,provenance_invalid:u,...f})=>f)},...o.metadata.test_runs===void 0?{}:{test_runs:o.metadata.test_runs.map(({executions:l,...d})=>d)}}:o.metadata,a=t===1&&s.tests?{...s,tests:[...s.tests].sort(CI)}:s;return{front_matter:Kt(a,Le),body:o.body}}function r_(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=Ke(e);return{metadata:Kt(n.metadata,Le),body:n.body}}function d_(e,t){if(!at.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return ye(N(gs(e,t)))}function ys(e,t){let n=d_(e,t);return t===2?[n,ye(N(gs(e,t,!0)))]:[n]}function ho(e){let t=gs(e.before,bt),n=gs(e.after,bt),r=r_(e.before),o=r_(e.after),i=s_.compare(r,o),s=NI(r,i),a=lm(e.author),c=a.harness?Object.fromEntries(Object.entries(Wc().provenance_outcomes).filter(([,u])=>u.resolver!==void 0&&u.status!=="resolved")):void 0,l=c===void 0||Object.keys(c).length===0?e.context:{...e.context,agent_provenance_outcomes:c},d={ts:e.nowIso,author:e.author,author_source:e.authorSource??cm(e.author),...a.harness?{agent_harness:a.harness}:{},...a.model?{agent_model:a.model}:{},...a.model_source?{agent_model_source:a.model_source}:{},...a.instance?{agent_instance:a.instance}:{},...a.provenance?{agent_provenance:a.provenance}:{},...a.episode?{agent_episode:a.episode}:{},op:e.op,patch:s,before_hash:ye(N(t)),after_hash:ye(N(n)),item_hash_version:bt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return br({...d,event_class:Fn(d)})}function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dl(e){return new w(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function u_(e){let t=e.ts.trim();if(t.length===0)return F();if(!Ci(t))throw dl("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw dl("History timestamp must not contain surrounding whitespace");return e.ts}function o_(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!Ci(n))throw dl("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function ul(e,t){let n=u_(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return wr(r)?JSON.stringify(o_(r,n)):e}return wr(e)?JSON.stringify(o_(e,n)):JSON.stringify(e)}async function DI(e,t,n){if(n===!1)return!0;if(typeof n=="string")return await Hr(e,ul(n,t)),await on(e),await tl(e),!0;if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e;return await Hr(o,ul(typeof r.line=="string"?r.line:r.entry??t,t)),await on(o),await tl(o),!0}async function ws(e,t){let n=await yt("history_append",{history_path:e,entry:t});if(n.handled&&await DI(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:u_(t)},o=br({...r,event_class:Fn(r)});await Im(e,o,async()=>{await Hr(e,ul(o,o))}),await on(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce8dfbdf-8471-5843-8179-5608140330e1")}catch{}})();var ml={metadata:{},body:""};function yo(){return structuredClone(ml)}function cn(e,t){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return ys(wo(e),t)}catch{}let n=ye(N({replay_fallback:!0,metadata:e.metadata,body:e.body}));return t===2?[n,n]:[n]}function m_(e,t,n,r){let o=cn(e,n),i=cn(t,n);return{beforeHashes:o,afterHashes:i,pairIndex:o.findIndex((s,a)=>s===r.before_hash&&i[a]===r.after_hash),beforeIndex:o.indexOf(r.before_hash),afterIndex:i.indexOf(r.after_hash)}}function wo(e){return{metadata:e.metadata,body:e.body}}function _l(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=Ke(e);return{metadata:Kt(t.metadata,Le),body:t.body}}function f_(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function PI(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function bo(e){return Array.isArray(e)?e.filter(PI).map(t=>({...t,path:f_(t.path),from:typeof t.from=="string"?f_(t.from):void 0})):[]}function LI(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function kr(e,t){try{let n=bo(t),r=pl.applyPatch(structuredClone(e),n,!0,!1).newDocument;return LI(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function MI(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&at.includes(t)))]}function __(e){return e!==void 0&&!at.includes(e)}function $I(e,t){return e!==void 0?[e]:t===void 0?[...at]:[t]}function g_(e){let t=an(e);if(!t.ok)return t.error;let n=hs(e);return n.ok?void 0:n.error}function FI(e,t){let n=g_(e);if(n)return{ok:!1,error:n};let r=kr(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function jI(e,t){let n=g_(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function Un(e){let t=yo(),n,r,o=[];for(let i=0;i<e.length;i+=1){let s=e[i],a=s.item_hash_version,c=__(a);c&&o.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${i+1}`);let l=FI(s,t);if(!l.ok)return{ok:!1,errors:[...o,`verify_failed:${l.error}:entry_${i+1}`]};if(c){t=l.document,n=void 0,r=void 0;continue}let u=$I(a,r).map(m=>({version:m,match:m_(t,l.document,m,s)})),f=u.find(({match:m})=>m.pairIndex>=0);if(f===void 0){let m=u.some(({match:g})=>g.beforeIndex>=0);return{ok:!1,errors:[...o,`verify_failed:${m?"after":"before"}_hash_mismatch:entry_${i+1}`]}}let p=f.version;t=l.document,n=p,r=a??r}return o.length>0?{ok:!1,errors:o,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function zn(e){let t=Un(e);return{ok:t.ok,errors:t.errors}}function p_(e,t){try{return{ok:!0,document:pl.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function UI(e,t){let n=structuredClone(e),r=0,o=0;for(let a of bo(t)){let c=p_(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=p_(n,{...a,op:"add"});if(l.ok){n=l.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function gl(e){let t=MI(e);if(t.length===1)return t[0];let n=Un(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:bt}function zI(e,t){let n=kr(e,t.patch);if(n.ok)return{next:n.document,patch:t.patch,repaired:!1,converted:0,skipped:0};let r=UI(e,t.patch);return{next:r.document,patch:pl.compare(e,r.document),repaired:!0,converted:r.convertedReplaceToAdd,skipped:r.skippedOps}}function vo(e,t=gl(e),n={}){let r=e.findIndex(p=>__(p.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=yo(),i=[],s=[],a=0,c=0,l=0,d=0,u,f=t!==1||e.some(p=>p.item_hash_version!==void 0);for(let p=0;p<e.length;p+=1){let m=e[p];jI(m,p);let g=zI(o,m),{next:y,patch:b,repaired:v,converted:A,skipped:I}=g;l+=A,d+=I,c+=Number(v);let x=m_(o,y,t,m);u===void 0||n.continuousHashSurface!==!0?u=[x.pairIndex,x.beforeIndex,x.afterIndex,Math.min(u??0,x.beforeHashes.length-1)].find(M=>M>=0):u=Math.min(u,x.beforeHashes.length-1);let P=x.beforeHashes[u],S=x.afterHashes[u],E=P!==m.before_hash||S!==m.after_hash;E&&(a+=1);let $={...m,patch:b,before_hash:P,after_hash:S};f?$.item_hash_version=t:delete $.item_hash_version;let Q=$.item_hash_version!==m.item_hash_version;(E||v||Q)&&($=vr(m,$,{retainOriginalPatch:v})),i.push($),s.push({index:p+1,rehashed:E,patch_repaired:v,converted_replace_to_add:A,skipped_ops:I}),o=y}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:l,skippedOps:d,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function ln(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
20
24
|
`)}
|
|
21
|
-
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="
|
|
25
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var Er="-",y_=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function ko(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function hl(e){return e.replace(/\r\n/g,`
|
|
26
|
+
`)}function w_(e){let t=hl(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
|
|
27
|
+
`);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
|
|
28
|
+
`)}function HI(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&e[o+1]===","){n+=",",o+=1;continue}if(i==="\\"&&e[o+1]!==void 0){n+=`${i}${e[o+1]}`,o+=1;continue}if(i==='"'){r=!r,n+=i;continue}if(i===","&&!r){t.push(n),n="";continue}n+=i}return n.trim()&&t.push(n),t}function b_(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function qI(e){let t=e.indexOf("="),n=e.indexOf(":"),r=t>=0,o=n>=0;return r&&o?Math.min(t,n):r?t:o?n:-1}function BI(e,t){if((t==="--add"||t==="--add-glob")&&(/[./\\]/.test(e)||/\.[a-z]{1,6}$/i.test(e.trim())))return"For file/doc paths use: path=<file-path>[,scope=project|global]. The scope field is optional and defaults to project (example: path=src/api.ts or path=README.md,scope=project). ";if(t!=="--event")return"";let n=e.toLowerCase(),r=n.includes("recur_")||n.includes("recurrence")?' Recurrence list values must stay in one field and use "|" delimiters (for example recur_by_weekday=mon|wed or recur_by_month_day=1|15).':"",o=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${r}${o}`}function h_(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=BI(e,t);return`Invalid ${t} value "${r}". Expected key=value entries separated by commas. `+o+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${t} ${Er} to read piped stdin input.`}function GI(e){let t=w_(e).trim();if(t.length===0||!t.includes(`
|
|
29
|
+
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=hl(t).split(`
|
|
30
|
+
`).map(i=>i.trim()).filter(i=>i.length>0);for(let i of o){let s=i.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(s){let a=s[1].trim();n[a]=b_(s[3].trim()),r=a;continue}if(r&&y_.has(r.toLowerCase())){n[r]=`${n[r]}
|
|
31
|
+
${i}`;continue}return null}return n}function Sr(e,t){let n=w_(e).trim();if(!n)throw new w(`${t} cannot be empty`,h.USAGE);let r=GI(n);if(r)return r;let o={},i,s=HI(n);for(let a of s){let c=qI(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new w(h_(e,t),h.USAGE);let d=b_(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&y_.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new w(h_(e,t),h.USAGE)}return o}var VI=/^[A-Za-z]:[\\/]/,WI=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function yl(e){let t=e.trim();return VI.test(t)?!1:WI.test(t)}function v_(e,t,n,r){if(!(r||!e.includes(",")))throw new w(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,h.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function xr(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new w(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,h.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new w(`${t} provides key "${i}" more than once after case normalization.`,h.USAGE);e[s]=e[i],delete e[i]}}}async function KI(e){if(process.stdin.isTTY===!0)throw new w(`${e} value "${Er}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,h.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(hl(r))}),process.stdin.on("error",o=>{n(o)})})}function Eo(){let e,t,n=async i=>{if(t&&t!==i)throw new w(`Only one option may use "${Er}" stdin token per command invocation. Already used by ${t}.`,h.USAGE);return t=i,e||(e=KI(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==Er?i:await n(s)},resolveList:async(i,s,a=!0)=>{if(!a)return i;if(!i)return;let c=i.map((u,f)=>u.trim()===Er?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new w(`${s} accepts "${Er}" stdin token at most once per command invocation`,h.USAGE);let l=await n(s),d=[...i];return d[c[0]]=l,d}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d5434c7-544b-5061-89eb-6e4074e58e30")}catch{}})();var E_=Object.freeze({pm_item_scalar_missing:!0});function Tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function Ne(e){return e===void 0?E_:e}function vt(e){return ye(N(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function wl(e,t){let n=Me(e);if(n)throw new w(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,h.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new w(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,h.GENERIC_FAILURE)}}return r}function dn(e){return N({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function JI(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&dn(e[r])===dn(t[r]);)r+=1;return r}function xl(e,t,n){wl(e,"base");let r=wl(t,"ours"),o=wl(n,"theirs"),i=JI(r,o);if(i===r.length&&i===o.length)return{merged:ln(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:ln(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:ln(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let s=r.slice(i),a=new Set(s.map(dn)),c=o.slice(i).filter(u=>!a.has(dn(u))),l=[...s,...c].sort((u,f)=>{let p=me(u.ts,f.ts);if(p!==0)return p;let m=a.has(dn(u)),g=a.has(dn(f));return m!==g?Number(g)-Number(m):dn(u).localeCompare(dn(f))}),d=vo([...r.slice(0,i),...l],void 0,{continuousHashSurface:!0});if(d.skippedOps>0)throw new w(`History union cannot preserve ${d.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,h.GENERIC_FAILURE);return{merged:ln(d.entries),strategy:"union_reanchor",common_entries:i,entries_from_ours:s.length,entries_from_theirs:c.length,entries_total:d.entries.length,reanchored:!0}}function bl(e,t){let n=Me(e);if(n)throw new w(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,h.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new w(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,h.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new w(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,h.GENERIC_FAILURE);r.push(a)}return r}function bs(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
22
32
|
`)}
|
|
23
|
-
`}function
|
|
24
|
-
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as
|
|
25
|
-
`}}function
|
|
26
|
-
`);let s=await
|
|
27
|
-
`)}return i}async function xd(e,t){let n;try{n=await lv(e)}catch(a){let c=await Iv(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],o=0,i=[],s=(a,c)=>{if(o+=1,i.length>=bo)return;let l=a.slice(0,-5);i.push({evidence_source:t,reason:c,...Cd(l)?{receipt_id:l}:{candidate_name_hash:se(a)}})};for(let a of n.sort((c,l)=>c.localeCompare(l))){if(!a.endsWith(".json"))continue;let c=await Ov(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c.reason)}return{receipts:r,invalid_evidence_count:o,invalid_evidence:i,invalid_evidence_truncated:o>i.length}}async function Iv(e,t,n=dv){if(!H(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(o){if(!H(o))return!1;let i=oe.dirname(r);if(i===r)return!0;r=i}}async function Ov(e,t,n){let r;try{r=await Rd(oe.join(e,t))}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let o;try{o=JSON.parse(r)}catch{return{reason:"candidate_invalid_json"}}if(!Fs(o,n)||t!==mn(o.id))return{reason:"schema_or_identity_invalid"};let{preferred:i,evidence_source:s,...a}=o;return{receipt:{...a,requested_preference:o.requested_preference??i??"ours",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function tt(e,t={}){let n=await Ls(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await xd(n,"clone_local"),o=t.pmRoot??oe.join(e,".agents","pm"),i=await xd(Ms(o),"durable"),s=new Map(i.receipts.map(l=>[l.id,l])),a=0,c=[];for(let l of r.receipts){let d=s.get(l.id);if(d!==void 0&&wo(d)!==wo(l)){s.delete(l.id),a+=1,r.invalid_evidence.length+i.invalid_evidence.length+c.length<bo&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:l.id});continue}s.set(l.id,d===void 0?l:Cv(l,d))}return{receipts:[...s.values()].filter(l=>(t.includeReconciled||l.state==="pending")&&(t.includeLossless!==!1||l.decisions.length>0)).sort((l,d)=>l.created_at.localeCompare(d.created_at)),invalid_evidence_count:r.invalid_evidence_count+i.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...i.invalid_evidence,...c].slice(0,bo),invalid_evidence_truncated:r.invalid_evidence_truncated||i.invalid_evidence_truncated||r.invalid_evidence_count+i.invalid_evidence_count+a>bo,clone_local_evidence_resolved:n!==null}}async function Dd(e,t={}){return(await tt(e,t)).receipts}function Pd(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function $s(e,t,n={}){let r=await Ls(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let o=t.evidence_source??"clone_local";if(!Fs(t,o))throw new Error("Merge receipt trusted settlement input failed schema validation.");let i=q(),s=oe.join(r,mn(t.id)),a=await Id(e,t.item_path),c=a===null?null:oe.join(Ms(a),mn(t.id)),d=(await Promise.all([Sd({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:i}),...c===null?[]:[Sd({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:i})]])).filter(f=>f!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=wo(t);if(new Set([u,...d.map(f=>f.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let f of d)await j(f.path,f.content)}async function Rv(e){let t=await Dd(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:q()}}async function Nv(e){let t=await tt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:q()}}import{readFile as dk,writeFile as uk}from"node:fs/promises";import fk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var Bt=new Set(Se),Dv=Object.freeze({get size(){return Bt.size},has(e){return Bt.has(e)},entries(){return Bt.entries()},keys(){return Bt.keys()},values(){return Bt.values()},forEach(e,t){Bt.forEach(n=>e.call(t,n,n,Dv))},[Symbol.iterator](){return Bt.values()}});function Pv(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Lv(e){return typeof e!="string"?null:$i(e)}function Mv(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Pv(r.name),i=Lv(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new h(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,g.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function nt(e){return[...Mv(e).keys()].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var ce={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ce,D=e=>typeof e=="boolean"?{ok:!0,value:e}:ce;function U(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?ce:{ok:!0,value:t}}function F(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ce}function A(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ce;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ce;r.push(i.value)}return{ok:!0,value:r}}}function Us(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:ce}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function vo(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ce;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ce;n[r]=i.value}return{ok:!0,value:n}}}function N(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ce;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ce;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var Fv=N({key:w,values:A(w),required:m(D),aliases:m(A(w)),description:m(w)}),$v=N({command:F("create","update"),option:w,required:m(D),visible:m(D),enabled:m(D)}),jv=N({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(A(w)),required_create_fields:m(A(w)),required_create_repeatables:m(A(w)),options:m(A(Fv)),command_option_policies:m(A($v))}),Uv=N({id:w,aliases:m(A(w)),roles:m(A(F(...Sr))),description:m(w),order:m(U())}),zv=N({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(A(w)),description:m(w),type:m(F(...Zt)),commands:m(A(F(...Ar))),repeatable:m(D),required:m(D),required_on_create:m(D),required_types:m(A(w)),allow_unset:m(D)}),qv=e=>{if(!Array.isArray(e)||e.length!==2)return ce;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ce:{ok:!0,value:[t,n]}},Bv=N({type:w,allowed_transitions:A(qv)}),Gv=m(N({version:m(U({int:!0})),files:m(N({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(A(Uv)),fields:m(A(zv)),workflow:m(N({draft_status:m(w),open_status:m(w),in_progress_status:m(w),blocked_status:m(w),close_status:m(w),canceled_status:m(w)})),type_workflows:m(A(Bv)),unknown_field_policy:m(F(...xr))})),Hv=m(N({preset:m(F(...vc)),ownership_enforcement:m(F("none","warn","strict")),create_mode_default:m(F("progressive","strict")),close_validation_default:m(F("off","warn","strict")),require_close_reason:m(D),parent_reference:m(F("warn","strict_error")),metadata_profile:m(F("core","strict","custom")),force_required_for_stale_lock:m(D),create_default_type:m(w),workflow_enforcement:m(F("off","warn","strict")),duplicate_detection_mode:m(F("off","advisory","strict")),duplicate_detection_threshold:m(U({min:0,max:1})),duplicate_detection_limit:m(U({int:!0,min:0,max:20}))})),Vv=N({name:w,disabled:m(D),require_trusted:m(D),require_provenance:m(D),sandbox_profile:m(F("none","restricted","strict")),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w))}),js=F("block","warn"),Wv=e=>typeof e=="string"?js(e):N({global:m(js),project:m(js)})(e),Kv=m(N({mode:m(F("off","warn","enforce")),trust_mode:m(F("off","warn","enforce")),pm_max_version_exceeded_mode:m(Wv),require_provenance:m(D),trusted_extensions:m(A(w)),default_sandbox_profile:m(F("none","restricted","strict")),allowed_extensions:m(A(w)),blocked_extensions:m(A(w)),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w)),extension_overrides:m(A(Vv))})),Gt=Us(128),Yv=N({harness:Us(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(A(Gt,64)),model_environment_keys:m(A(Gt,64)),session_environment_keys:m(A(Gt,64)),provenance_environment_keys:m(vo(A(Gt,64))),provenance_resolvers:m(vo(F("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(A(Gt,64)),argv_markers:m(A(Gt,64)),client_names:m(A(Gt,64))}),Xv=N({version:U({int:!0}),id_prefix:w,ids:m(N({token_length:m(U({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(N({probes_enabled:m(D),identity_vocabulary:m(N({version:U({int:!0,positive:!0}),aliases:vo(Us(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:A(Yv)})),mutation_guard:m(N({require_attributed_author:m(D),secret_guard:m(F("off","advise","block")),stale_in_progress_hours:m(U({int:!0,positive:!0}))})),item_format:m(F("toon","json_markdown")),locks:N({ttl_seconds:U({int:!0}),wait_ms:m(U({int:!0,min:0}))}),checkpoints:m(N({retention_days:m(U({int:!0,positive:!0}))})),output:N({default_format:F("toon","json")}),ux:m(N({deprecation_hints:m(D)})),history:m(N({missing_stream:F("auto_create","strict_error"),compact_policy:m(N({enabled:m(D),max_entries:m(U({int:!0,positive:!0})),trigger:m(F("health_warn","auto"))}))})),validation:m(N({sprint_release_format:F("warn","strict_error"),parent_reference:m(F("warn","strict_error")),metadata_profile:m(F("core","strict","custom")),metadata_required_fields:m(A(w)),lifecycle_stale_blocker_reason_patterns:m(A(w)),lifecycle_closure_like_blocked_reason_patterns:m(A(w)),lifecycle_closure_like_resolution_patterns:m(A(w)),lifecycle_closure_like_actual_result_patterns:m(A(w)),estimate_defaults_by_type:m(vo(U({int:!0,positive:!0})))})),governance:Hv,workflow:m(N({definition_of_done:A(w)})),testing:m(N({record_results_to_items:D,allow_untrusted_linked_tests:m(D)})),telemetry:m(N({enabled:D,first_run_prompt_completed:m(D),capture_level:m(F("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(U({int:!0,positive:!0}))})),agent_guidance:m(N({prompt_completed:m(D),declined:m(D),declined_at:m(w),template_version:m(U({int:!0,positive:!0})),last_checked_files:m(A(w))})),item_types:m(N({definitions:A(jv)})),schema:Gv,context:m(N({default_depth:m(F("brief","standard","deep")),activity_limit:m(U({int:!0,positive:!0})),stale_threshold_days:m(U({int:!0,positive:!0})),sections:m(N({hierarchy:m(D),activity:m(D),progress:m(D),recently_created:m(D),unparented:m(D),blockers:m(D),files:m(D),workload:m(D),staleness:m(D),tests:m(D)}))})),extensions:N({enabled:A(w),disabled:A(w),policy:Kv}),search:N({score_threshold:U(),hybrid_semantic_weight:m(U()),max_results:U({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(U()),embedding_batch_size:U({int:!0}),embedding_timeout_ms:m(U({int:!0})),scanner_max_batch_retries:U({int:!0}),provider:m(w),corpus_fields:m(A(w)),mutation_refresh_policy:m(F("cache_only","semantic_configured","semantic_auto")),query_expansion:m(N({enabled:m(D),provider:m(w)})),rerank:m(N({enabled:m(D),model:m(w),top_k:m(U({int:!0,positive:!0}))})),bm25:m(N({k1:m(U()),b:m(U())}))}),providers:N({openai:N({base_url:w,api_key:w,model:w}),ollama:N({base_url:w,model:w})}),vector_store:N({adapter:m(w),collection_name:m(w),qdrant:N({url:w,api_key:w}),lancedb:N({path:w})})});function Ld(e){let t=Xv(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Kn from"node:path";import rt from"node:fs/promises";import zs from"node:path";import{randomUUID as Jv}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9ad8a9f-de6e-5bce-8685-844f1129d5fb")}catch{}})();function Zv(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let n=t,r=n.id,o=n.pid,i=n.owner,s=n.created_at,a=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||typeof s!="string"||typeof a!="number"||!Number.isFinite(a)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,created_at:s,ttl_seconds:a},warnings:[]}}async function jd(e){try{let t=await rt.readFile(e,"utf8");return await Me({path:e,scope:"project"}),Zv(t)}catch(t){return H(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function qs(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Ud(e,t){await Ee({path:e,scope:"project",op:t})}function Qv(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:q(),ttl_seconds:n}}async function eE(e,t,n,r){await rt.mkdir(zs.dirname(e),{recursive:!0});let o=await rt.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Qv(t,n,r),null,2)}
|
|
28
|
-
|
|
29
|
-
`,"utf8")}catch{return await Bs(e),null}return t}async function _E(e){let t;try{let r=await rt.stat(e);if(t=Date.now()-r.mtimeMs,t<=aE)return!1}catch(r){return H(r)}let n=await Hd(e);return n!==null&&mE(n.pid)&&t<=cE?!1:Bs(e)}async function gE(e,t){let n=`${e}${sE}`,r=await $d(n);if(r!==null)return async()=>Fd(n,r.token);if(!await _E(n))return null;let o=await $d(n);return o===null?null:async()=>Fd(n,o.token)}async function hE(e){let t=await gE(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await jd(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!qd(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(fE(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=iE)throw Gd(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await zd(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function $e(e,t,n,r,o=!1,i=!0,s){let a=await Ge("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let p=uE(a.result);if(p)return async()=>{await Promise.resolve(p()),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}let c=ll(e,t),l=lE(s),d=Date.now(),u=0,f=nE;for(;;)try{return await eE(c,t,r,n),async()=>{await zd(c,"lock:release"),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!qs(p,"EEXIST"))throw new h(`Failed to acquire lock for ${t}: ${Je(p)}`,g.GENERIC_FAILURE);let _=await jd(c);if(qd(_.info,n)){let b=await hE({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:u,waitBudgetMs:l,startedAtMs:d,fallbackLockInfo:_});if(_=b.lockInfo,b.staleRemovalCounted&&(u+=1),b.shouldRetryCreate)continue}let y=Date.now()-d;if(l===0||y>=l)throw Gd(t,_.info,l===0?0:y);await dE(Math.min(f,l-y)),f=Math.min(f*2,rE)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9027d972-ce29-5511-ba81-27e17d97446e")}catch{}})();var fe="_workspace";function Eo(e){return Kn.join(e,"history",`${fe}.jsonl`)}function yE(e,t=e.length){let n=qn();for(let r of e.slice(0,t))n=pn(n,r.patch).document;return Bn(n)}function bE(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function wE(e){throw new h(`Workspace history verification failed: ${e.join(", ")}`,g.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function vE(e,t){let n=Kn.resolve(t),r=Kn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Kn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Gs(e){let t=await _t(Eo(e),fe),n=zt(t);n.ok||wE(n.errors);let r=bE(t.length===0?yi:yE(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=vE(e,Kn.resolve(e,c));if(l=await Q(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d377bc4-c624-561c-9856-405c82099070")}catch{}})();var EE={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Vd=120;function Hs(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Kd(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var kE=Kd(EE),Wd=new WeakMap;function TE(e){let t=Wd.get(e);if(t)return t;let n=Kd(e);return Wd.set(e,n),n}function Yd(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Vd;if(t){let o=TE(t).get(n);if(Hs(o))return Math.floor(o)}let r=kE.get(n);return Hs(r)?Math.floor(r):Vd}function Xd(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Hs(r)||(t[o]=Math.floor(r))}return t}import{stat as SE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60da76ea-0bd3-56a9-a2bc-d88ba76e1013")}catch{}})();var ko=new Map;function Jd(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function AE(e){try{let t=await SE(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function vt(e){let t=Jd(e),n=await Promise.all(t.map(r=>AE(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Yn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function Zd(e){return ko.get(e)}function To(e,t){let n=Jd(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));ko.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Ht(e){if(e){ko.delete(e);return}ko.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b95183e-9fd3-55cf-9059-8736f692e96e")}catch{}})();var tu=Symbol("pm.settings.persist_source"),CE=128,IE=new Set(["off","advisory","strict"]);function Qd(e){return structuredClone(gi[e])}function OE(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:ie.governance.preset}function RE(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),IE.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function Vt(e){let t=e.governance??{},n=OE(t.preset),r=RE(t);if(n==="custom"){let s=Qd("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Qd(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function nu(){return structuredClone(ie)}function NE(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:ie.search.mutation_refresh_policy}function DE(e){return typeof e=="boolean"?e:ie.search.query_expansion.enabled}function PE(e){return typeof e!="string"?ie.search.query_expansion.provider:e.trim()}function LE(e){return typeof e=="boolean"?e:ie.search.rerank.enabled}function ME(e){return typeof e!="string"?ie.search.rerank.model:e.trim()}function FE(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:ie.search.rerank.top_k}function $E(e){if(typeof e!="string")return ie.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,CE);return n.length>0?n:ie.vector_store.collection_name}function Vs(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function jE(e,t){let n=e.schema,r=Vs(n?.statuses),o=Vs(n?.fields),i=Vs(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:xo(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:xo(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function ru(e,t){Object.defineProperty(e,tu,{value:t,writable:!0,configurable:!0,enumerable:!1})}function UE(e){let t=e[tu];if(!(!t||typeof t!="object"))return t}function Ao(e){let t=structuredClone(e.settings),n=UE(e.settings);return n&&ru(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function zE(e,t,n){let r=ut(t);return[n,be(e,r.files.types,_e.types),be(e,r.files.statuses,_e.statuses),be(e,r.files.fields,_e.fields),be(e,r.files.workflows,_e.workflows)]}async function qE(e,t,n){let r=await vt(t);To(e,{tracked_paths:t,signatures:r,value:Ao(n)})}async function BE(e,t,n){try{await qE(e,t,n)}catch{Ht(e)}}function eu(e,t){return e.find(n=>n.path===t)}function GE(e,t,n){for(let r of n){let o=eu(e,r),i=eu(t,r);if(!o||!i||!Yn([o],[i]))return!1}return!0}async function Ws(e,t,n,r,o){try{let i=await vt(t);if(!GE(r,i,o)){Ht(e);return}To(e,{tracked_paths:t,signatures:i,value:Ao(n)})}catch{Ht(e)}}function Xn(e){return{settings:nu(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function HE(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function VE(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function WE(e){let t=ie.agent_guidance,n=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:VE(e?.last_checked_files??t.last_checked_files)}}function je(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function KE(e){return e==="off"||e==="warn"||e==="enforce"?e:ie.extensions.policy.mode}function YE(e){return e==="off"||e==="warn"||e==="enforce"?e:ie.extensions.policy.trust_mode}function ou(e){return e==="none"||e==="restricted"||e==="strict"?e:ie.extensions.policy.default_sandbox_profile}function XE(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=ou(e.sandbox_profile));let r=je(e.allowed_capabilities),o=je(e.blocked_capabilities),i=je(e.allowed_surfaces),s=je(e.blocked_surfaces),a=je(e.allowed_commands),c=je(e.blocked_commands),l=je(e.allowed_actions),d=je(e.blocked_actions),u=je(e.allowed_services),f=je(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),l.length>0&&(n.allowed_actions=l),d.length>0&&(n.blocked_actions=d),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function JE(e){let t=new Map;for(let n of e??[]){let r=XE(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Ks(e){return e==="block"||e==="warn"?e:void 0}function ZE(e){if(typeof e=="string")return Ks(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Ks(e.global),n=Ks(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function ke(e,t){return je(e?.[t]??ie.extensions.policy[t])}function QE(e){let t=ZE(e?.pm_max_version_exceeded_mode);return{mode:KE(e?.mode),trust_mode:YE(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ke(e,"trusted_extensions"),default_sandbox_profile:ou(e?.default_sandbox_profile),allowed_extensions:ke(e,"allowed_extensions"),blocked_extensions:ke(e,"blocked_extensions"),allowed_capabilities:ke(e,"allowed_capabilities"),blocked_capabilities:ke(e,"blocked_capabilities"),allowed_surfaces:ke(e,"allowed_surfaces"),blocked_surfaces:ke(e,"blocked_surfaces"),allowed_commands:ke(e,"allowed_commands"),blocked_commands:ke(e,"blocked_commands"),allowed_actions:ke(e,"allowed_actions"),blocked_actions:ke(e,"blocked_actions"),allowed_services:ke(e,"allowed_services"),blocked_services:ke(e,"blocked_services"),extension_overrides:JE(e?.extension_overrides??ie.extensions.policy.extension_overrides)}}function ek(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).filter(n=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(n))}function So(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function tk(e){return Array.isArray(e)?e:[]}function nk(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:ek(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:So(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:So(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:So(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:So(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Xd(e.validation?.estimate_defaults_by_type)}}function rk(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function ok(e,t){return{...t.search,...e.search,mutation_refresh_policy:NE(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:DE(e.search?.query_expansion?.enabled),provider:PE(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:LE(e.search?.rerank?.enabled),model:ME(e.search?.rerank?.model),top_k:FE(e.search?.rerank?.top_k)}}}function ik(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:$E(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function sk(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function ak(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,sections:{...t.context.sections,...e.context?.sections}}}function ck(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function xo(e){let t=(e??[]).map(r=>Gr(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function lk(e){let t=nu(),n=Vt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:sk(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:nk(e,t,n),governance:n,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:rk(e,t),agent_guidance:WE(e.agent_guidance??t.agent_guidance),item_types:{definitions:xo(e.item_types?.definitions)},schema:ut(e.schema??t.schema),context:ak(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:QE(e.extensions.policy??t.extensions.policy)},search:ok(e,t),providers:ck(e,t),vector_store:ik(e,t)}}async function Jn(e){let t=ve(e),n=[t];await Me({path:t,scope:"project"});let r=Zd(e);if(r){let l=await vt(r.tracked_paths);if(Yn(l,r.signatures))return Ao(r.value)}let o=await vt([t]),i;try{i=await Q(t)}catch{return Xn("settings_read_fs_error")}if(i===null){let l=Xn();return await Ws(e,[t],l,o,[t]),l}let s=await vt([t]);if(!Yn(o,s))return Ht(e),Jn(e);let a;try{a=JSON.parse(i)}catch{let l=Xn("settings_read_invalid_json");return await Ws(e,[t],l,s,[t]),l}let c=Ld(a);if(!c.success){let l=Xn("settings_read_invalid_schema");return await Ws(e,[t],l,s,[t]),l}try{let l=lk(c.data),d=zE(e,l.schema,t);n=d;let u=await vt(d),f=await Mc(e,l.schema),p=await Fc(e,l.schema),_=await vt(d),y={...l,item_types:{definitions:xo([...l.item_types.definitions,...tk(p.type_definitions_from_file)])},schema:p.schema};ru(y,jE(c.data,y));let b={settings:y,metadata:{has_explicit_item_format:HE(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(E=>`runtime_schema_bootstrap_created:${E}`),...p.warnings]};return f.created_paths.length===0?Yn(u,_)?To(e,{tracked_paths:d,signatures:_,value:Ao(b)}):Ht(e):Ht(e),b}catch{let l=Xn("settings_read_merge_failed");return await BE(e,n,l),l}}async function te(e){return(await Jn(e)).settings}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8046a5-06aa-58f8-b347-e757086082d1")}catch{}})();var Xs=["item","history","relationship","json"];function pk(e){let t=e.trim().toLowerCase();if(Xs.includes(t))return t;throw new h(`Unknown merge artifact "${e}". Supported values: ${Xs.join(", ")}.`,g.USAGE)}function mk(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new h(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,g.USAGE)}async function Ys(e,t){try{return await dk(e,"utf8")}catch{throw new h(`Cannot read merge ${t} file at ${e}.`,g.NOT_FOUND)}}async function _k(e){let t=re(process.cwd(),e.path);return await B(ve(t))?te(t):null}function gk(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function hk(e,t){let n=pk(e.artifact),r=mk(e.prefer),o=fk.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Ys(e.basePath,"base"),Ys(e.oursPath,"ours"),Ys(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=Is(i,s,a);c=p.merged,u.history={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="relationship"){let p=Os(i,s,a);c=p.merged,u.relationship={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="item"){let p=await _k(t),_=gk(e.itemPath??o,p),y=nt(Y()),b=Rs(i,s,a,{format:_,schema:p?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"stable_value_order"});if(c=b.merged,d.push(...b.conflict_fields),u.item={fields_from_theirs:b.fields_from_theirs,union_fields:b.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0){let E=Ce(c,{format:_,schema:p?.schema,extensionFieldNames:y}),v=E.metadata,C=[...new Set([...b.fields_from_theirs,...b.union_fields,...b.conflict_decisions.map(k=>k.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:b.fields_from_theirs,unionFields:b.union_fields,mergedFieldHashes:Object.fromEntries(C.map(k=>[k,se(R(k==="body"?E.body:v[k]))])),decisions:b.conflict_decisions}}}else{let p=Ns(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await uk(o,c,"utf8"),l!==void 0){let p=await Nd(l);p!==null&&(u.receipt=We(p))}let f=[];if(d.length>0){let p=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${d.join(", ")}; the item driver kept the direction-independent stable value. ${p} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:d,...u,guidance:f,generated_at:q()}}import Zs from"node:fs/promises";import Co from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b0efe32-43f5-51ed-b1d5-5c26a3ae5bf0")}catch{}})();function Et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Qs(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:`pm ${t.map(n=>`'${n.replaceAll("'",`'"'"'`)}'`).join(" ")}`,suggested_retry_args:t}}function Io(e){return new h(`Tracker root is not a directory at ${e}.`,g.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function Js(e){return new h(`Tracker root is not readable at ${e}.`,g.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function yk(e){let t=Co.resolve(e),n=Co.parse(t).root,r=Co.dirname(t);for(;r!==n;){let o;try{o=await Zs.stat(r)}catch(i){if(Et(i,"ENOTDIR"))throw Io(e);if(!Et(i,"ENOENT"))throw i;r=Co.dirname(r);continue}if(!o.isDirectory())throw Io(e);return}}async function Zn(e){let t;try{t=await Zs.stat(e)}catch(n){throw Et(n,"ENOENT")?(await yk(e),new h(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,g.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:Qs(e)})):Et(n,"ENOTDIR")?Io(e):Et(n,"EACCES")||Et(n,"EPERM")?Js(e):n}if(!t.isDirectory())throw Io(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Js(e);try{await(await Zs.opendir(e)).close()}catch(n){throw Et(n,"EACCES")||Et(n,"EPERM")?Js(e):n}}async function Oe(e){if(await Zn(e),!await B(ve(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:Qs(e)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{readFile as Ro,realpath as ea,writeFile as Ek}from"node:fs/promises";import{execFile as kk}from"node:child_process";import Z from"node:path";import{promisify as Tk}from"node:util";import bk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var iu=["runtime/","search/","locks/","transactions/","checkpoints/"];function su(e){let t=e.replaceAll("\\","/");return bk.isAbsolute(e)||t===".."||t.startsWith("../")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var wk="PM_SOURCE_CONTEXT_ACCESS",vk="PM_ALLOW_SOURCE_CONTEXT_WRITES";function au(e){let t=e[wk],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[vk]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var ta=Tk(kk),Qn="# pm-cli:merge-drivers:start",na="# pm-cli:merge-drivers:end",Wt="# pm-cli:merge-drivers:v2:start",Oo="# pm-cli:merge-drivers:v2:end",Sk="merge-fence";function cu(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function uu(){let e=an(import.meta.url,["../../.."]);return`${cu(process.execPath)} ${cu(Z.join(e,"dist","cli.js"))}`}var fu=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function pu(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=au(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=re(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:Z.resolve(r),workspace_start:Z.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?re(e.cwd,".agents/pm"):re(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function kt(e){try{let{stdout:t}=await ta("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ea(t.trim())}catch{return null}}async function mu(e){let t=await kt(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function ra(e,t){return Z.relative(e,t).replaceAll("\\","/")}function Ke(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function lu(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Ak(e,t){let n=lu(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=lu(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(Z.basename(n.value))||Z.basename(r.value)!=="cli.js"||Z.basename(Z.dirname(r.value))!=="dist"||!await B(n.value)||!await B(r.value))return!1;try{let o=Z.dirname(Z.dirname(r.value)),i=JSON.parse(await Ro(Z.join(o,"package.json"),"utf8")),s=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function No(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ke(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ke(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${Ke(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${Ke(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ke(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ke(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ke(`${n}settings.json`)} merge=pm-json`),r.push(`${Ke(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ke(`${n}extensions/**`)} -merge`),r.push(`${Ke(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function du(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function _u(e,t,n){let r=Z.join(e,".gitattributes"),o="";try{o=await Ro(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&H(l)))throw l}let i=[Wt,...t,Oo].join(`
|
|
30
|
-
`),a=du(du(o,Wt,Oo),Qn,na).trimEnd(),c=`${a.length>0?`${a}
|
|
33
|
+
`}function YI(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Tl(e,t,n){bl(e,"base");let r=bl(t,"ours"),o=bl(n,"theirs"),i=Math.min(r.length,o.length),s=0;for(;s<i&&r[s].eventId===o[s].eventId;)s+=1;if(s===r.length&&s===o.length)return{merged:bs(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:bs(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:bs(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(f=>f.eventId)),l=o.slice(s).filter(f=>!c.has(f.eventId)),d=[...a,...l].sort((f,p)=>{if(f.timestamp!==void 0&&p.timestamp!==void 0){let y=me(f.timestamp,p.timestamp);if(y!==0)return y}else{if(f.timestamp===void 0&&p.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let m=c.has(f.eventId),g=c.has(p.eventId);return m!==g?Number(g)-Number(m):0}),u=YI([...r.slice(0,s),...d]);return{merged:bs(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var S_=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],XI=["acceptance_criteria"],x_=["updated_at"];function Hn(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:N(e)===N(t)}function k_(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(d=>N(d))),i=r(t),s=new Set(i.map(d=>N(d))),a=r(n),c=new Set(a.map(d=>N(d))),l=i.filter(d=>{let u=N(d);return!o.has(u)||c.has(u)});for(let d of a){let u=N(d);!s.has(u)&&!o.has(u)&&l.push(d)}return l}function So(e){if(typeof e!="object"||e===null||Array.isArray(e))return N(e);let{provenance:t,...n}=e;return N(n)}function ZI(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function QI(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(So)),i=r(t),s=new Set(i.map(So)),a=r(n),c=new Set(a.map(So)),l=i.filter(d=>{let u=So(d);return!o.has(u)||c.has(u)});for(let d of a){let u=So(d);!s.has(u)&&!o.has(u)&&l.push(ZI(d))}return l}function eC(e,t){return me(String(e),String(t))>=0?e:t}function T_(e,t,n,r){return Hn(t,n)?{value:t,from_theirs:!1,conflict:!1}:Hn(e,t)?{value:n,from_theirs:!0,conflict:!1}:Hn(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function A_(e,t,n,r,o,i,s){let a=T_(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(o==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=me(i,s);if(o==="latest_document_update"&&c!==0){let d=c<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"document_updated_at",retained_side:d?"theirs":"ours"}}let l=N(Ne(n)).localeCompare(N(Ne(t)))<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:l?"theirs":"ours"}}function vl(e){return{...e.metadata}}function kl(e,t,n){try{let r=Ke($e(e,n),n),o=Object.entries(r.metadata).find(([,i])=>Tr(i))?.[0];if(o!==void 0)throw new TypeError(`metadata field ${o} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw new w(`Item merge input (${t}) is not a readable item document: ${String(r)}`,h.GENERIC_FAILURE)}}function tC(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?QI(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?k_(ko(e.baseValue),ko(e.oursValue),ko(e.theirsValue)).join("; "):k_(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Hn(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function nC(e){let t=A_(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:Ne(e.baseValue),ours:Ne(e.oursValue),theirs:Ne(e.theirsValue),retained:Ne(t.value),discarded:Ne(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function rC(e,t,n,r,o,i,s){let a=new Set([...S_,...XI]),c=new Set(x_),l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,f)=>u.localeCompare(f)),d={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of l){let f=e[u],p=t[u],m=n[u];if(!tC({field:u,baseValue:f,oursValue:p,theirsValue:m,unionFieldSet:a,accumulator:d})){if(c.has(u)){d.merged[u]=eC(p,m);continue}nC({field:u,baseValue:f,oursValue:p,theirsValue:m,preferred:r,conflictResolution:o,oursUpdatedAt:i,theirsUpdatedAt:s,accumulator:d})}}return d}function Al(e,t,n,r={}){let o=r.preferred??"ours",i=r.conflictResolution??"preferred_side",s=e.trim().length>0,a=kl(t,"ours",r),c=kl(n,"theirs",r),l=s?kl(e,"base",r):a,d=s?vl(l):{},u=vl(a),f=vl(c),{merged:p,conflictFields:m,fieldsFromTheirs:g,unionFields:y,conflictDecisions:b}=rC(d,u,f,o,i,a.metadata.updated_at,c.metadata.updated_at),v=A_(s?l.body:"",a.body,c.body,o,i,a.metadata.updated_at,c.metadata.updated_at);return v.conflict?(m.push("body"),b.push({field:"body",base:Ne(s?l.body:""),ours:Ne(a.body),theirs:Ne(c.body),retained:Ne(v.value),discarded:Ne(v.from_theirs?a.body:c.body),retained_side:v.retained_side,resolution_basis:v.resolution_basis})):v.from_theirs&&g.push("body"),{merged:xn({metadata:p,body:v.value},r),conflict_fields:m,fields_from_theirs:g,union_fields:y,conflict_decisions:b,requested_preference:o,requested_preference_applied:i==="preferred_side",conflict_resolution:i}}function El(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sl(e,t){let n=Me(e);if(n)throw new w(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,h.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new w(`JSON merge input (${t}) is not valid JSON.`,h.GENERIC_FAILURE)}}function oC(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=l=>{let d=new Map;for(let u of l){let f=N(u);d.set(f,(d.get(f)??0)+1)}return d},o=r(e),i=r(t),s=r(n);for(let[l,d]of o)if((i.get(l)??0)<d||(s.get(l)??0)<d)return null;let a=new Map(i),c=[];for(let l of n){let d=N(l),u=a.get(d)??0;u>0?a.set(d,u-1):c.push(l)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function iC(e,t,n,r,o,i,s){if(!El(t)||!El(n))return null;let a=El(e)?e:{},c={},l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u));for(let d of l){let u=o.length>0?`${o}.${d}`:d,f=sC(a,t,n,d,r,u,i,s);f!==void 0&&(c[d]=f)}return c}function I_(e,t,n,r,o,i,s){if(Hn(t,n))return t;let a=oC(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(o),a.merged;let c=iC(e,t,n,r,o,i,s);if(c!==null)return c;let l=T_(e,t,n,r);return l.conflict?i.push(o):l.from_theirs&&s.push(o),l.value}function sC(e,t,n,r,o,i,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),l=Object.prototype.hasOwnProperty.call(n,r),d=Object.prototype.hasOwnProperty.call(e,r);if(c&&l)return I_(e[r],t[r],n[r],o,i,s,a);if(c){if(d&&Hn(e[r],t[r])){a.push(i);return}return d?(s.push(i),o==="theirs"?void 0:t[r]):t[r]}if(!(d&&Hn(e[r],n[r])))return d?(s.push(i),o==="theirs"?n[r]:void 0):(a.push(i),n[r])}function Il(e,t,n,r={}){let o=r.preferred??"ours",i=Sl(e,"base"),s=Sl(t,"ours"),a=Sl(n,"theirs"),c=[],l=[],d=I_(i,s,a,o,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
|
|
34
|
+
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as uC}from"node:child_process";import{randomUUID as fC}from"node:crypto";import{readdir as pC,stat as mC}from"node:fs/promises";import ge from"node:path";import{promisify as _C}from"node:util";import{constants as C_}from"node:fs";import{lstat as aC,open as cC}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var lC={lstat:aC,open:cC};function dC(e){return e.O_NOFOLLOW??0}async function O_(e,t,n=lC){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let o=await n.open(e,C_.O_RDONLY|dC(C_));try{let i=await o.stat();if(!i.isFile()||i.size>t)return null;let s=Buffer.alloc(i.size),a=0;for(;a<s.length;){let{bytesRead:l}=await o.read(s,a,s.length-a,a);if(l===0)break;a+=l}return(await o.stat()).size===i.size&&a===i.size?s.toString("utf8",0,a):null}finally{await o.close()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dfdd6f10-e11f-59e8-a16f-507dc40d5b31")}catch{}})();var gC=_C(uC),hC=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,yC=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Ol=2048,wC=16*1024*1024,bC=64,vC=1e5,vs=100,kC=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source"]);function Bn(e){return hC.test(e)}var EC=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),Rl="bounded_non_sensitive_scalars_v1",SC=new Set(["open","in_progress","blocked","closed","canceled"]),xC=new Set(["risk","confidence","severity"]),TC=new Set(["low","medium","high","critical"]),M_=new Map([["priority",new Set([0,1,2,3,4].map(N))],["status",new Set([...SC].map(N))],...[...xC].map(e=>[e,new Set([...TC].map(N))])]);async function Nl(e){try{let{stdout:t}=await gC("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function $_(e,t){let n=ge.dirname(ge.resolve(e,t));for(let r=0;r<12;r+=1){if(await U(ge.join(n,"settings.json")))return n;let o=ge.dirname(n);if(o===n)break;n=o}return null}function Dl(e){return ge.join(e,"merge-receipts")}function Ar(e){return`${e}.json`}function qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function F_(e,t){return Object.keys(e).every(n=>t.has(n))}function R_(e){return Array.isArray(e)&&e.length<=Ol&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function xo(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>vC||r.depth>bC)return!1;if(Array.isArray(r.value))for(let o of r.value)t.push({value:o,depth:r.depth+1});else if(qn(r.value))for(let o of Object.values(r.value))t.push({value:o,depth:r.depth+1})}return!0}function AC(e){if(!qn(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[F_(e,EC),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),xo(e.base),xo(e.ours),xo(e.theirs),xo(e.retained),xo(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function IC(e){if(!qn(e))return!1;let t=Object.entries(e);return t.length<=Ol&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function CC(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ge.posix.isAbsolute(e))return!1;let n=ge.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ge.posix.basename(n,ge.posix.extname(n))===t}function OC(e){return!R_(e.fields_from_theirs)||!R_(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Ol||!e.decisions.every(AC)?!1:e.merged_field_hashes===void 0||IC(e.merged_field_hashes)}function RC(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],o=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===Rl)&&o.includes(e.evidence_source)}function NC(e){return typeof e.created_at=="string"&&Ot(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Ot(e.reconciled_at))}function N_(e,t){if(!qn(t)||Cl(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||M_.get(e)?.has(N(r))===!0)&&vt(r)===t.pm_value_hash}function DC(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&N_(r.field,r.retained)&&N_(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,o)=>r+(qn(o.retained)&&Object.hasOwn(o.retained,"pm_value")?1:0)+(qn(o.discarded)&&Object.hasOwn(o.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===Rl)}function j_(e,t){if(!qn(e))return"required_fields";for(let n of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,n))return"required_fields";return e.version!==1||!F_(e,kC)?"required_fields":typeof e.id!="string"||!Bn(e.id)?"receipt_id":typeof e.item_id!="string"||!yC.test(e.item_id)?"item_id":CC(e.item_path,e.item_id)?OC(e)?RC(e)?NC(e)?t==="durable"&&!DC(e)?"durable_decisions":null:"timestamps":"enums":"collections":"item_path"}function U_(e,t){return j_(e,t)===null}async function z_(e){return O_(e,wC)}async function D_(e){let t;try{t=await(e.readReceipt??z_)(e.receiptPath)}catch(i){if(ut(i))return null;throw i}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!U_(n,e.evidenceSource)||n.id!==e.receiptId||ge.basename(e.receiptPath)!==Ar(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...o}=n;return{path:e.receiptPath,fingerprint:ks(n),content:`${JSON.stringify({...o,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
|
|
35
|
+
`}}function ks(e){return ye(N({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,decisions:Ft(e).decisions}))}function PC(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function Ft(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Cl(t.retained)??vt(Tr(t.retained)?void 0:t.retained),discarded_hash:Cl(t.discarded)??vt(Tr(t.discarded)?void 0:t.discarded)}))}}function Cl(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function P_(e,t){let n=Tr(t),r=vt(n?void 0:t);return!n&&(t===null||M_.get(e)?.has(N(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}async function H_(e){let t=await Nl(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,o=ge.basename(r,ge.extname(r)),i={version:1,id:fC(),item_path:r.replaceAll("\\","/"),item_id:o,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions),state:"pending",created_at:F(),value_availability:"clone_local"};await Jt(t),await H(ge.join(t,Ar(i.id)),`${JSON.stringify(i,null,2)}
|
|
36
|
+
`);let s=await $_(e.cwd,i.item_path);if(s!==null){let a=Dl(s),c=i.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:P_(u.field,u.retained),discarded:P_(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),l=c.reduce((u,f)=>u+(Object.hasOwn(f.retained,"pm_value")?1:0)+(Object.hasOwn(f.discarded,"pm_value")?1:0),0),d={...i,decisions:c,value_availability:l===0?"hash_only":l===c.length*2?"bounded_inline":"mixed",value_policy:Rl};await Jt(a),await H(ge.join(a,Ar(i.id)),`${JSON.stringify(d,null,2)}
|
|
37
|
+
`)}return i}async function L_(e,t){let n;try{n=await pC(e)}catch(a){let c=await LC(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],o=0,i=[],s=(a,c)=>{if(o+=1,i.length>=vs)return;let l=a.slice(0,-5);i.push({evidence_source:t,reason:c.reason,...c.validation_error===void 0?{}:{validation_error:c.validation_error},...Bn(l)?{receipt_id:l}:{candidate_name_hash:ye(a)}})};for(let a of n.sort((c,l)=>c.localeCompare(l))){if(!a.endsWith(".json"))continue;let c=await MC(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c)}return{receipts:r,invalid_evidence_count:o,invalid_evidence:i,invalid_evidence_truncated:o>i.length}}async function LC(e,t,n=mC){if(!j(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(o){if(!j(o))return!1;let i=ge.dirname(r);if(i===r)return!0;r=i}}async function MC(e,t,n){let r;try{r=await z_(ge.join(e,t))}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let o;try{o=JSON.parse(r)}catch{return{reason:"candidate_invalid_json"}}let i=j_(o,n);if(i!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(i)?"identity_invalid":"schema_invalid",validation_error:i};let s=o;if(t!==Ar(s.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...l}=s;return{receipt:{...l,requested_preference:s.requested_preference??a??"ours",requested_preference_applied:s.requested_preference_applied??(s.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:s.conflict_resolution??"preferred_side",evidence_source:n}}}async function ft(e,t={}){let n=await Nl(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await L_(n,"clone_local"),o=t.pmRoot??ge.join(e,".agents","pm"),i=await L_(Dl(o),"durable"),s=new Map(i.receipts.map(l=>[l.id,l])),a=0,c=[];for(let l of r.receipts){let d=s.get(l.id);if(d!==void 0&&ks(d)!==ks(l)){s.delete(l.id),a+=1,r.invalid_evidence.length+i.invalid_evidence.length+c.length<vs&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:l.id});continue}s.set(l.id,d===void 0?l:PC(l,d))}return{receipts:[...s.values()].filter(l=>(t.includeReconciled||l.state==="pending")&&(t.includeLossless!==!1||l.decisions.length>0)).sort((l,d)=>l.created_at.localeCompare(d.created_at)),invalid_evidence_count:r.invalid_evidence_count+i.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...i.invalid_evidence,...c].slice(0,vs),invalid_evidence_truncated:r.invalid_evidence_truncated||i.invalid_evidence_truncated||r.invalid_evidence_count+i.invalid_evidence_count+a>vs,clone_local_evidence_resolved:n!==null}}async function q_(e,t={}){return(await ft(e,t)).receipts}function Es(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Pl(e,t,n={}){let r=await Nl(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let o=t.evidence_source??"clone_local";if(!U_(t,o))throw new Error("Merge receipt trusted settlement input failed schema validation.");let i=F(),s=ge.join(r,Ar(t.id)),a=await $_(e,t.item_path),c=a===null?null:ge.join(Dl(a),Ar(t.id)),d=(await Promise.all([D_({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:i}),...c===null?[]:[D_({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:i})]])).filter(f=>f!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=ks(t);if(new Set([u,...d.map(f=>f.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let f of d)await H(f.path,f.content)}async function $C(e){let t=await q_(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:F()}}async function FC(e){let t=await ft(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:F()}}import{readFile as KO,writeFile as JO}from"node:fs/promises";import YO from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var Gn=new Set(Le),jC=Object.freeze({get size(){return Gn.size},has(e){return Gn.has(e)},entries(){return Gn.entries()},keys(){return Gn.keys()},values(){return Gn.values()},forEach(e,t){Gn.forEach(n=>e.call(t,n,n,jC))},[Symbol.iterator](){return Gn.values()}});function UC(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function zC(e){return typeof e!="string"?null:Wi(e)}function HC(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=UC(r.name),i=zC(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new w(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,h.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function pt(e){return[...HC(e).keys()].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var Ee={ok:!1},k=e=>typeof e=="string"?{ok:!0,value:e}:Ee,z=e=>typeof e=="boolean"?{ok:!0,value:e}:Ee;function Y(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?Ee:{ok:!0,value:t}}function G(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:Ee}function C(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return Ee;let r=[];for(let o of n){let i=e(o);if(!i.ok)return Ee;r.push(i.value)}return{ok:!0,value:r}}}function Ml(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:Ee}function _(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Ss(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ee;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return Ee;n[r]=i.value}return{ok:!0,value:n}}}function L(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Ee;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return Ee;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var qC=L({key:k,values:C(k),required:_(z),aliases:_(C(k)),description:_(k)}),BC=L({command:G("create","update"),option:k,required:_(z),visible:_(z),enabled:_(z)}),GC=L({name:k,description:_(k),default_status:_(k),folder:_(k),aliases:_(C(k)),required_create_fields:_(C(k)),required_create_repeatables:_(C(k)),options:_(C(qC)),command_option_policies:_(C(BC))}),VC=L({id:k,aliases:_(C(k)),roles:_(C(G(...rr))),description:_(k),order:_(Y())}),WC=L({key:k,metadata_key:_(k),front_matter_key:_(k),cli_flag:_(k),cli_aliases:_(C(k)),description:_(k),type:_(G(...Wt)),commands:_(C(G(...or))),repeatable:_(z),required:_(z),required_on_create:_(z),required_types:_(C(k)),allow_unset:_(z)}),KC=e=>{if(!Array.isArray(e)||e.length!==2)return Ee;let[t,n]=e;return typeof t!="string"||typeof n!="string"?Ee:{ok:!0,value:[t,n]}},JC=L({type:k,allowed_transitions:C(KC)}),YC=_(L({version:_(Y({int:!0})),files:_(L({types:_(k),statuses:_(k),fields:_(k),workflows:_(k)})),statuses:_(C(VC)),fields:_(C(WC)),workflow:_(L({draft_status:_(k),open_status:_(k),in_progress_status:_(k),blocked_status:_(k),close_status:_(k),canceled_status:_(k)})),type_workflows:_(C(JC)),unknown_field_policy:_(G(...ki))})),XC=_(L({preset:_(G(...Zu)),ownership_enforcement:_(G("none","warn","strict")),create_mode_default:_(G("progressive","strict")),close_validation_default:_(G("off","warn","strict")),require_close_reason:_(z),parent_reference:_(G("warn","strict_error")),metadata_profile:_(G("core","strict","custom")),force_required_for_stale_lock:_(z),create_default_type:_(k),workflow_enforcement:_(G("off","warn","strict")),duplicate_detection_mode:_(G("off","advisory","strict")),duplicate_detection_threshold:_(Y({min:0,max:1})),duplicate_detection_limit:_(Y({int:!0,min:0,max:20}))})),ZC=L({name:k,disabled:_(z),require_trusted:_(z),require_provenance:_(z),sandbox_profile:_(G("none","restricted","strict")),allowed_capabilities:_(C(k)),blocked_capabilities:_(C(k)),allowed_surfaces:_(C(k)),blocked_surfaces:_(C(k)),allowed_commands:_(C(k)),blocked_commands:_(C(k)),allowed_actions:_(C(k)),blocked_actions:_(C(k)),allowed_services:_(C(k)),blocked_services:_(C(k))}),Ll=G("block","warn"),QC=e=>typeof e=="string"?Ll(e):L({global:_(Ll),project:_(Ll)})(e),eO=_(L({mode:_(G("off","warn","enforce")),trust_mode:_(G("off","warn","enforce")),pm_max_version_exceeded_mode:_(QC),require_provenance:_(z),trusted_extensions:_(C(k)),default_sandbox_profile:_(G("none","restricted","strict")),allowed_extensions:_(C(k)),blocked_extensions:_(C(k)),allowed_capabilities:_(C(k)),blocked_capabilities:_(C(k)),allowed_surfaces:_(C(k)),blocked_surfaces:_(C(k)),allowed_commands:_(C(k)),blocked_commands:_(C(k)),allowed_actions:_(C(k)),blocked_actions:_(C(k)),allowed_services:_(C(k)),blocked_services:_(C(k)),extension_overrides:_(C(ZC))})),Vn=Ml(128),tO=L({harness:Ml(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:_(C(Vn,64)),model_environment_keys:_(C(Vn,64)),session_environment_keys:_(C(Vn,64)),provenance_environment_keys:_(Ss(C(Vn,64))),provenance_resolvers:_(Ss(G("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:_(C(Vn,64)),argv_markers:_(C(Vn,64)),client_names:_(C(Vn,64))}),nO=L({version:Y({int:!0}),id_prefix:k,ids:_(L({token_length:_(Y({int:!0,min:4,max:12}))})),author_default:k,agent_identity:_(L({probes_enabled:_(z),identity_vocabulary:_(L({version:Y({int:!0,positive:!0}),aliases:Ss(Ml(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:C(tO)})),mutation_guard:_(L({require_attributed_author:_(z),secret_guard:_(G("off","advise","block")),stale_in_progress_hours:_(Y({int:!0,positive:!0}))})),item_format:_(G("toon","json_markdown")),locks:L({ttl_seconds:Y({int:!0}),wait_ms:_(Y({int:!0,min:0}))}),checkpoints:_(L({retention_days:_(Y({int:!0,positive:!0}))})),output:L({default_format:G("toon","json")}),ux:_(L({deprecation_hints:_(z)})),history:_(L({missing_stream:G("auto_create","strict_error"),compact_policy:_(L({enabled:_(z),max_entries:_(Y({int:!0,positive:!0})),trigger:_(G("health_warn","auto"))}))})),validation:_(L({sprint_release_format:G("warn","strict_error"),parent_reference:_(G("warn","strict_error")),metadata_profile:_(G("core","strict","custom")),metadata_required_fields:_(C(k)),lifecycle_stale_blocker_reason_patterns:_(C(k)),lifecycle_closure_like_blocked_reason_patterns:_(C(k)),lifecycle_closure_like_resolution_patterns:_(C(k)),lifecycle_closure_like_actual_result_patterns:_(C(k)),estimate_defaults_by_type:_(Ss(Y({int:!0,positive:!0})))})),governance:XC,workflow:_(L({definition_of_done:C(k)})),testing:_(L({record_results_to_items:z,allow_untrusted_linked_tests:_(z)})),telemetry:_(L({enabled:z,first_run_prompt_completed:_(z),capture_level:_(G("minimal","redacted","max")),endpoint:_(k),installation_id:_(k),retention_days:_(Y({int:!0,positive:!0}))})),agent_guidance:_(L({prompt_completed:_(z),declined:_(z),declined_at:_(k),template_version:_(Y({int:!0,positive:!0})),last_checked_files:_(C(k))})),item_types:_(L({definitions:C(GC)})),schema:YC,context:_(L({default_depth:_(G("brief","standard","deep")),activity_limit:_(Y({int:!0,positive:!0})),stale_threshold_days:_(Y({int:!0,positive:!0})),sections:_(L({hierarchy:_(z),activity:_(z),progress:_(z),recently_created:_(z),unparented:_(z),blockers:_(z),files:_(z),workload:_(z),staleness:_(z),tests:_(z)}))})),extensions:L({enabled:C(k),disabled:C(k),policy:eO}),search:L({score_threshold:Y(),hybrid_semantic_weight:_(Y()),max_results:Y({int:!0}),embedding_model:k,embedding_corpus_max_characters:_(Y()),embedding_batch_size:Y({int:!0}),embedding_timeout_ms:_(Y({int:!0})),scanner_max_batch_retries:Y({int:!0}),provider:_(k),corpus_fields:_(C(k)),mutation_refresh_policy:_(G("cache_only","semantic_configured","semantic_auto")),query_expansion:_(L({enabled:_(z),provider:_(k)})),rerank:_(L({enabled:_(z),model:_(k),top_k:_(Y({int:!0,positive:!0}))})),bm25:_(L({k1:_(Y()),b:_(Y())}))}),providers:L({openai:L({base_url:k,api_key:k,model:k}),ollama:L({base_url:k,model:k})}),vector_store:L({adapter:_(k),collection_name:_(k),qdrant:L({url:k,api_key:k}),lancedb:L({path:k})})});function B_(e){let t=nO(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import To from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4df21a17-43c0-5b63-adf3-657699e6a058")}catch{}})();var Ae="_workspace";function xs(e){return To.join(e,"history",`${Ae}.jsonl`)}function rO(e,t=e.length){let n=yo();for(let r of e.slice(0,t))n=kr(n,r.patch).document;return wo(n)}function oO(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function iO(e){throw new w(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function sO(e,t){let n=To.resolve(t),r=To.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||To.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function $l(e){let t=await Mt(xs(e),Ae),n=zn(t);n.ok||iO(n.errors);let r=oO(t.length===0?Ra:rO(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=sO(e,To.resolve(e,c));if(l=await Z(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(N(u)===N(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d377bc4-c624-561c-9856-405c82099070")}catch{}})();var aO={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},G_=120;function Fl(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function W_(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var cO=W_(aO),V_=new WeakMap;function lO(e){let t=V_.get(e);if(t)return t;let n=W_(e);return V_.set(e,n),n}function K_(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return G_;if(t){let o=lO(t).get(n);if(Fl(o))return Math.floor(o)}let r=cO.get(n);return Fl(r)?Math.floor(r):G_}function J_(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Fl(r)||(t[o]=Math.floor(r))}return t}import{stat as dO}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60da76ea-0bd3-56a9-a2bc-d88ba76e1013")}catch{}})();var Ts=new Map;function Y_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function uO(e){try{let t=await dO(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function un(e){let t=Y_(e),n=await Promise.all(t.map(r=>uO(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Ao(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function X_(e){return Ts.get(e)}function As(e,t){let n=Y_(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));Ts.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Wn(e){if(e){Ts.delete(e);return}Ts.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5b95183e-9fd3-55cf-9059-8736f692e96e")}catch{}})();var eg=Symbol("pm.settings.persist_source"),fO=128,pO=new Set(["off","advisory","strict"]);function Z_(e){return structuredClone(Ca[e])}function mO(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:he.governance.preset}function _O(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),pO.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function fn(e){let t=e.governance??{},n=mO(t.preset),r=_O(t);if(n==="custom"){let s=Z_("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Z_(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function tg(){return structuredClone(he)}function gO(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:he.search.mutation_refresh_policy}function hO(e){return typeof e=="boolean"?e:he.search.query_expansion.enabled}function yO(e){return typeof e!="string"?he.search.query_expansion.provider:e.trim()}function wO(e){return typeof e=="boolean"?e:he.search.rerank.enabled}function bO(e){return typeof e!="string"?he.search.rerank.model:e.trim()}function vO(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:he.search.rerank.top_k}function kO(e){if(typeof e!="string")return he.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,fO);return n.length>0?n:he.vector_store.collection_name}function jl(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function EO(e,t){let n=e.schema,r=jl(n?.statuses),o=jl(n?.fields),i=jl(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Os(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:Os(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function ng(e,t){Object.defineProperty(e,eg,{value:t,writable:!0,configurable:!0,enumerable:!1})}function SO(e){let t=e[eg];if(!(!t||typeof t!="object"))return t}function Cs(e){let t=structuredClone(e.settings),n=SO(e.settings);return n&&ng(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function xO(e,t,n){let r=_t(t);return[n,Re(e,r.files.types,xe.types),Re(e,r.files.statuses,xe.statuses),Re(e,r.files.fields,xe.fields),Re(e,r.files.workflows,xe.workflows)]}async function TO(e,t,n){let r=await un(t);As(e,{tracked_paths:t,signatures:r,value:Cs(n)})}async function AO(e,t,n){try{await TO(e,t,n)}catch{Wn(e)}}function Q_(e,t){return e.find(n=>n.path===t)}function IO(e,t,n){for(let r of n){let o=Q_(e,r),i=Q_(t,r);if(!o||!i||!Ao([o],[i]))return!1}return!0}async function Ul(e,t,n,r,o){try{let i=await un(t);if(!IO(r,i,o)){Wn(e);return}As(e,{tracked_paths:t,signatures:i,value:Cs(n)})}catch{Wn(e)}}function Io(e){return{settings:tg(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function CO(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function OO(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function RO(e){let t=he.agent_guidance,n=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:OO(e?.last_checked_files??t.last_checked_files)}}function mt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function NO(e){return e==="off"||e==="warn"||e==="enforce"?e:he.extensions.policy.mode}function DO(e){return e==="off"||e==="warn"||e==="enforce"?e:he.extensions.policy.trust_mode}function rg(e){return e==="none"||e==="restricted"||e==="strict"?e:he.extensions.policy.default_sandbox_profile}function PO(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=rg(e.sandbox_profile));let r=mt(e.allowed_capabilities),o=mt(e.blocked_capabilities),i=mt(e.allowed_surfaces),s=mt(e.blocked_surfaces),a=mt(e.allowed_commands),c=mt(e.blocked_commands),l=mt(e.allowed_actions),d=mt(e.blocked_actions),u=mt(e.allowed_services),f=mt(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),l.length>0&&(n.allowed_actions=l),d.length>0&&(n.blocked_actions=d),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function LO(e){let t=new Map;for(let n of e??[]){let r=PO(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function zl(e){return e==="block"||e==="warn"?e:void 0}function MO(e){if(typeof e=="string")return zl(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=zl(e.global),n=zl(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function Xe(e,t){return mt(e?.[t]??he.extensions.policy[t])}function $O(e){let t=MO(e?.pm_max_version_exceeded_mode);return{mode:NO(e?.mode),trust_mode:DO(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:Xe(e,"trusted_extensions"),default_sandbox_profile:rg(e?.default_sandbox_profile),allowed_extensions:Xe(e,"allowed_extensions"),blocked_extensions:Xe(e,"blocked_extensions"),allowed_capabilities:Xe(e,"allowed_capabilities"),blocked_capabilities:Xe(e,"blocked_capabilities"),allowed_surfaces:Xe(e,"allowed_surfaces"),blocked_surfaces:Xe(e,"blocked_surfaces"),allowed_commands:Xe(e,"allowed_commands"),blocked_commands:Xe(e,"blocked_commands"),allowed_actions:Xe(e,"allowed_actions"),blocked_actions:Xe(e,"blocked_actions"),allowed_services:Xe(e,"allowed_services"),blocked_services:Xe(e,"blocked_services"),extension_overrides:LO(e?.extension_overrides??he.extensions.policy.extension_overrides)}}function FO(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).filter(n=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(n))}function Is(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function jO(e){return Array.isArray(e)?e:[]}function UO(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:FO(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Is(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Is(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Is(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Is(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:J_(e.validation?.estimate_defaults_by_type)}}function zO(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function HO(e,t){return{...t.search,...e.search,mutation_refresh_policy:gO(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:hO(e.search?.query_expansion?.enabled),provider:yO(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:wO(e.search?.rerank?.enabled),model:bO(e.search?.rerank?.model),top_k:vO(e.search?.rerank?.top_k)}}}function qO(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:kO(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function BO(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function GO(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,sections:{...t.context.sections,...e.context?.sections}}}function VO(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Os(e){let t=(e??[]).map(r=>qi(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function WO(e){let t=tg(),n=fn({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:BO(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:UO(e,t,n),governance:n,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:zO(e,t),agent_guidance:RO(e.agent_guidance??t.agent_guidance),item_types:{definitions:Os(e.item_types?.definitions)},schema:_t(e.schema??t.schema),context:GO(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:$O(e.extensions.policy??t.extensions.policy)},search:HO(e,t),providers:VO(e,t),vector_store:qO(e,t)}}async function pn(e){let t=be(e),n=[t];await Ue({path:t,scope:"project"});let r=X_(e);if(r){let l=await un(r.tracked_paths);if(Ao(l,r.signatures))return Cs(r.value)}let o=await un([t]),i;try{i=await Z(t)}catch{return Io("settings_read_fs_error")}if(i===null){let l=Io();return await Ul(e,[t],l,o,[t]),l}let s=await un([t]);if(!Ao(o,s))return Wn(e),pn(e);let a;try{a=JSON.parse(i)}catch{let l=Io("settings_read_invalid_json");return await Ul(e,[t],l,s,[t]),l}let c=B_(a);if(!c.success){let l=Io("settings_read_invalid_schema");return await Ul(e,[t],l,s,[t]),l}try{let l=WO(c.data),d=xO(e,l.schema,t);n=d;let u=await un(d),f=await mf(e,l.schema),p=await _f(e,l.schema),m=await un(d),g={...l,item_types:{definitions:Os([...l.item_types.definitions,...jO(p.type_definitions_from_file)])},schema:p.schema};ng(g,EO(c.data,g));let y={settings:g,metadata:{has_explicit_item_format:CO(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(b=>`runtime_schema_bootstrap_created:${b}`),...p.warnings]};return f.created_paths.length===0?Ao(u,m)?As(e,{tracked_paths:d,signatures:m,value:Cs(y)}):Wn(e):Wn(e),y}catch{let l=Io("settings_read_merge_failed");return await AO(e,n,l),l}}async function oe(e){return(await pn(e)).settings}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5dc5f70c-0b04-51bb-983b-49b15be11587")}catch{}})();var Bl=["item","history","relationship","json"];function XO(e){let t=e.trim().toLowerCase();if(Bl.includes(t))return t;throw new w(`Unknown merge artifact "${e}". Supported values: ${Bl.join(", ")}.`,h.USAGE)}function ZO(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new w(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,h.USAGE)}async function ql(e,t){try{return await KO(e,"utf8")}catch{throw new w(`Cannot read merge ${t} file at ${e}.`,h.NOT_FOUND)}}async function QO(e){let t=te(process.cwd(),e.path);return await U(be(t))?oe(t):null}function eR(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function tR(e,t){let n=XO(e.artifact),r=ZO(e.prefer),o=YO.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([ql(e.basePath,"base"),ql(e.oursPath,"ours"),ql(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=xl(i,s,a);c=p.merged,u.history={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="relationship"){let p=Tl(i,s,a);c=p.merged,u.relationship={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="item"){let p=await QO(t),m=eR(e.itemPath??o,p),g=pt(K()),y=Al(i,s,a,{format:m,schema:p?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"latest_document_update"});if(c=y.merged,d.push(...y.conflict_fields),u.item={fields_from_theirs:y.fields_from_theirs,union_fields:y.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let b=$e(c,{format:m,schema:p?.schema,extensionFieldNames:g}),v=b.metadata,A=[...new Set([...y.fields_from_theirs,...y.union_fields,...y.conflict_decisions.map(I=>I.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:y.fields_from_theirs,unionFields:y.union_fields,mergedFieldHashes:Object.fromEntries(A.map(I=>[I,vt(I==="body"?b.body:v[I])])),decisions:y.conflict_decisions}}}else{let p=Il(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await JO(o,c,"utf8"),l!==void 0){let p=await H_(l);p!==null&&(u.receipt=Ft(p))}let f=[];if(d.length>0){let p=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${d.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${p} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:d,...u,guidance:f,generated_at:F()}}import Vl from"node:fs/promises";import Rs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b0efe32-43f5-51ed-b1d5-5c26a3ae5bf0")}catch{}})();function mn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Wl(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:`pm ${t.map(n=>`'${n.replaceAll("'",`'"'"'`)}'`).join(" ")}`,suggested_retry_args:t}}function Ns(e){return new w(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function Gl(e){return new w(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function nR(e){let t=Rs.resolve(e),n=Rs.parse(t).root,r=Rs.dirname(t);for(;r!==n;){let o;try{o=await Vl.stat(r)}catch(i){if(mn(i,"ENOTDIR"))throw Ns(e);if(!mn(i,"ENOENT"))throw i;r=Rs.dirname(r);continue}if(!o.isDirectory())throw Ns(e);return}}async function Ir(e){let t;try{t=await Vl.stat(e)}catch(n){throw mn(n,"ENOENT")?(await nR(e),new w(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:Wl(e)})):mn(n,"ENOTDIR")?Ns(e):mn(n,"EACCES")||mn(n,"EPERM")?Gl(e):n}if(!t.isDirectory())throw Ns(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Gl(e);try{await(await Vl.opendir(e)).close()}catch(n){throw mn(n,"EACCES")||mn(n,"EPERM")?Gl(e):n}}async function Ie(e){if(await Ir(e),!await U(be(e)))throw new w(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:Wl(e)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{readFile as Ps,realpath as Kl,writeFile as sR}from"node:fs/promises";import{execFile as aR}from"node:child_process";import fe from"node:path";import{promisify as cR}from"node:util";import rR from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var og=["runtime/","search/","locks/","transactions/","checkpoints/"];function ig(e){let t=e.replaceAll("\\","/");return rR.isAbsolute(e)||t===".."||t.startsWith("../")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var oR="PM_SOURCE_CONTEXT_ACCESS",iR="PM_ALLOW_SOURCE_CONTEXT_WRITES";function sg(e){let t=e[oR],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[iR]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var Jl=cR(aR),Co="# pm-cli:merge-drivers:start",Yl="# pm-cli:merge-drivers:end",Kn="# pm-cli:merge-drivers:v2:start",Ds="# pm-cli:merge-drivers:v2:end",lR="merge-fence";function ag(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function dg(){let e=Je(import.meta.url,["../../.."]);return`${ag(process.execPath)} ${ag(fe.join(e,"dist","cli.js"))}`}var ug=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function fg(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=sg(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=te(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:fe.resolve(r),workspace_start:fe.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?te(e.cwd,".agents/pm"):te(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function Et(e){try{let{stdout:t}=await Jl("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Kl(t.trim())}catch{return null}}async function pg(e){let t=await Et(e);if(t===null)throw new w("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Xl(e,t){return fe.relative(e,t).replaceAll("\\","/")}function kt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function cg(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function dR(e,t){let n=cg(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=cg(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(fe.basename(n.value))||fe.basename(r.value)!=="cli.js"||fe.basename(fe.dirname(r.value))!=="dist"||!await U(n.value)||!await U(r.value))return!1;try{let o=fe.dirname(fe.dirname(r.value)),i=JSON.parse(await Ps(fe.join(o,"package.json"),"utf8")),s=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Ls(e,t){let n=e.length>0?`${e}/`:"",r=[`${kt(`${n}**/*.toon`)} merge=pm-item-toon`,`${kt(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${kt(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${kt(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${kt(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${kt(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${kt(`${n}settings.json`)} merge=pm-json`),r.push(`${kt(`${n}**/*.json`)} merge=pm-json`),r.push(`${kt(`${n}extensions/**`)} -merge`),r.push(`${kt(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function lg(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function mg(e,t,n){let r=fe.join(e,".gitattributes"),o="";try{o=await Ps(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&j(l)))throw l}let i=[Kn,...t,Ds].join(`
|
|
38
|
+
`),a=lg(lg(o,Kn,Ds),Co,Yl).trimEnd(),c=`${a.length>0?`${a}
|
|
31
39
|
|
|
32
40
|
`:""}${i}
|
|
33
|
-
`;return c===o?{path:r,changed:!1}:(n||await
|
|
34
|
-
`).map(v=>v.trim()).filter(v=>v.length>0):[],p=No(ra(r,n),t),_=new Set(f),y=new Set(p),b=p.filter(v=>!_.has(v)),E=f.filter(v=>!y.has(v));return{status:b.length>0||E.length>0?"drift":"ok",path:s,missing_patterns:b,stale_patterns:E,schema_scope:"project"}}async function ia(e){let t=uu(),n=[],r=[];for(let o of fu){let i=`merge.${o.key}.driver`,s=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await ta("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Ak(l,s)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function xk(e){let t;try{t=await mu(Z.resolve(e))}catch{return{status:"no_git"}}let n=ra(t,Z.resolve(e)),r=await te(e),o=Fe(void 0,r.author_default),i=await $e(e,Sk,r.locks.ttl_seconds,o,!1,Vt(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=Z.join(t,".gitattributes"),a;try{a=await Ro(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&H(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Wt)&&!a.includes(Qn))return{status:"not_installed",path:s};let c=await te(e),l=Do(c),d=await _u(t,No(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function Ck(e,t){let n=pu({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Oe(r);let o=await mu(n.workspace_start);return Ik({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function Ik(e){let t=Z.resolve(e.pmRoot),n=Z.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([ea(t),ea(n)])}catch(p){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=ra(i,o);if(su(s))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await te(o),c=Do(a),l=No(s,c),d=[],u=uu();for(let p of fu)d.push({key:`merge.${p.key}.name`,value:p.name}),d.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of d)await ta("git",["config","--local",p.key,p.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let f=await _u(i,l,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:f.path,changed:f.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:q()}}import{realpath as Qu}from"node:fs/promises";import nS from"node:path";import ef from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function gu(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function er(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?gu(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?gu(t):"root"}import UT from"node:fs/promises";import ir from"node:fs/promises";import CT from"node:path";import Ok from"node:fs/promises";import Rk from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="58fd6fef-9c13-5c6a-9110-b760461896aa")}catch{}})();function Nk(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function Dk(e,t){return new h(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,g.NOT_FOUND)}async function Pk(e,t){return await dt(Rk.dirname(e)),await(await Ok.open(e,"a")).close(),Ee({path:e,scope:"project",op:`${t}:history:auto_create`})}async function sa(e){return hu({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function hu(e){let t=Nk(e.itemIds),n=[],r=[];for(let o of t){let i=Be(e.pmRoot,o);if(!await B(i)){if(e.settings.history.missing_stream==="strict_error")throw Dk(o,e.commandLabel);r.push(...await Pk(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function Lk(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function _n(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function Tt(e,t){let n=Lk(t),r=_n(e);return r.startsWith(n)?r:`${n}${r}`}import pe from"node:fs/promises";import G from"node:path";import{createHash as Bk,randomUUID as Cu}from"node:crypto";import Kt from"node:fs/promises";import yu from"node:path";import{randomUUID as Mk}from"node:crypto";import{createRequire as Fk}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e94075b0-810d-506c-b6a2-ae322526c078")}catch{}})();var $k="metadata-query-index.sqlite",bu="4";function jk(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Po;function Uk(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?jk(t):null}function wu(){return Po!==void 0||(Po=Uk(process.versions.node,Fk(import.meta.url))),Po}function aa(e){return yu.join(e,"runtime",$k)}function zk(e){e.exec(`
|
|
41
|
+
`;return c===o?{path:r,changed:!1}:(n||await sR(r,c,"utf8"),{path:r,changed:!0})}function Ms(e){let t=de(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Zl(e,t){let n=fe.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let A=fe.join(i,".gitattributes");try{let x=await Ps(A,"utf8");if(x.includes(Kn)||x.includes(Co)){r=i,o=x;break}}catch{}let I=fe.dirname(i);if(I===i)break;i=I}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=fe.join(r,".gitattributes"),a=o.includes(Kn),c=a?Kn:Co,l=a?Ds:Yl,d=o.indexOf(c),u=o.indexOf(l),f=u>d?o.slice(d+c.length,u).split(`
|
|
42
|
+
`).map(v=>v.trim()).filter(v=>v.length>0):[],p=Ls(Xl(r,n),t),m=new Set(f),g=new Set(p),y=p.filter(v=>!m.has(v)),b=f.filter(v=>!g.has(v));return{status:y.length>0||b.length>0?"drift":"ok",path:s,missing_patterns:y,stale_patterns:b,schema_scope:"project"}}async function Oo(e){let t=dg(),n=[],r=[];for(let o of ug){let i=`merge.${o.key}.driver`,s=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await Jl("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await dR(l,s)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function _g(e){let t;try{t=await pg(fe.resolve(e))}catch{return{status:"no_git"}}let n=Xl(t,fe.resolve(e)),r=await oe(e),o=Ye(void 0,r.author_default),i=await ke(e,lR,r.locks.ttl_seconds,o,!1,fn(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=fe.join(t,".gitattributes"),a;try{a=await Ps(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&j(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Kn)&&!a.includes(Co))return{status:"not_installed",path:s};let c=await oe(e),l=Ms(c),d=await mg(t,Ls(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function uR(e,t){let n=fg({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Ie(r);let o=await pg(n.workspace_start);return fR({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function fR(e){let t=fe.resolve(e.pmRoot),n=fe.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([Kl(t),Kl(n)])}catch(p){throw new w(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=Xl(i,o);if(ig(s))throw new w(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let a=await oe(o),c=Ms(a),l=Ls(s,c),d=[],u=dg();for(let p of ug)d.push({key:`merge.${p.key}.name`,value:p.name}),d.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of d)await Jl("git",["config","--local",p.key,p.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new w(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let f=await mg(i,l,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:f.path,changed:f.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:F()}}import{readFile as F1}from"node:fs/promises";import j1 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var Ql=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),r};import Bt from"node:fs/promises";import Be from"node:path";import pR from"node:fs/promises";import mR from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="58fd6fef-9c13-5c6a-9110-b760461896aa")}catch{}})();function _R(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function gR(e,t){return new w(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,h.NOT_FOUND)}async function hR(e,t){return await Jt(mR.dirname(e)),await(await pR.open(e,"a")).close(),je({path:e,scope:"project",op:`${t}:history:auto_create`})}async function ed(e){return $s({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function $s(e){let t=_R(e.itemIds),n=[],r=[];for(let o of t){let i=gt(e.pmRoot,o);if(!await U(i)){if(e.settings.history.missing_stream==="strict_error")throw gR(o,e.commandLabel);r.push(...await hR(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import Ro from"node:fs/promises";import{createHash as yR}from"node:crypto";import hg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c6c65ef-115b-50e2-815e-84f6e91158cd")}catch{}})();var yg=9,wR="history-drift-cache.json";function wg(e){return hg.join(e,"runtime",wR)}async function bR(e){try{let t=await Ro.readFile(wg(e),"utf8"),n=JSON.parse(t);return n.version!==yg||n.history_item_hash_version!==bt||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!at.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&at.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function vR(e,t,n,r,o){let i=xs(e),s;try{s=await Ro.stat(i)}catch(l){return j(l)||o.unreadableStreams.push(Ae),!1}let a=o.missingStreams.length,c=await bg({itemId:Ae,historyPath:i,stat:s,cached:t[Ae],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.versionSkew&&o.versionSkews.push(Ae),c.verification.chainOk||o.chainMismatches.push(Ae),n[Ae]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function kR(e){return yR("sha256").update(e).digest("hex")}async function ER(e){let t=await Ro.readFile(e,"utf8"),n=kR(t);if(t.trim().length===0)return null;let r=[],o=null;for(let u of t.split(/\r?\n/)){let f=u.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),o=p.after_hash}if(!o)return null;let i=Un(r),s=r.some(u=>u.item_hash_version!==void 0&&!at.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,l=c!==void 0&&at.includes(c),d=l?c:i.item_hash_version;return{latestAfterHash:o,chainOk:i.ok,versionSkew:s,latestHashComparable:d!==void 0&&(!s||l||c===void 0),contentHash:n,itemHashVersion:d??bt}}function SR(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function gg(e,t,n){try{let r=await ER(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function bg(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(SR(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await gg(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await gg(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&at.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function xR(e,t,n,r){let o=gt(e,t.id),i;try{i=await Ro.stat(o)}catch(d){return(j(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await bg({itemId:t.id,historyPath:o,stat:i,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&(ys({metadata:c,body:a},s.verification.itemHashVersion).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function TR(e,t){if(!(t.unreadableStreams.includes(Ae)||t.chainMismatches.includes(Ae)||t.versionSkews.includes(Ae)))try{let n=await $l(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(Ae)}}async function Jn(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await bR(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await xR(e,f,l,r)&&(a=!0);let d=await vR(e,i,s,c,r);if(a||=d,await TR(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=wg(e);try{await Ro.mkdir(hg.dirname(f),{recursive:!0}),await H(f,JSON.stringify({version:yg,history_item_hash_version:bt,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[Ae]:[]])].sort((f,p)=>f.localeCompare(p));return{...r,driftedItems:u}}import vg from"node:fs/promises";import kg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f9ccbd-48d1-5eb3-82ae-3dd62427041c")}catch{}})();function AR(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:o,created_at:i,ttl_seconds:s}=n;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof s!="number"||!Number.isFinite(s)?null:{id:r,owner:o,created_at:i,ttl_seconds:s}}function IR(e,t,n){let r=AR(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let o=Date.parse(r.created_at);if(!Number.isFinite(o))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let i=n-o,s=Math.floor(i/1e3),a=i>r.ttl_seconds*1e3;return{detail:a?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:s,stale:a,reason:a?"expired":"active"}}}async function Eg(e,t){let n=t??Date.now(),r=kg.join(e,"locks"),o={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},i;try{i=(await vg.readdir(r)).filter(a=>a.endsWith(".lock")).sort()}catch(s){if(j(s))return o;throw s}for(let s of i){let a;try{a=await vg.readFile(kg.join(r,s),"utf8")}catch(l){if(j(l))continue;o.scanned+=1,o.unreadable_lock_count+=1;continue}o.scanned+=1;let{detail:c}=IR(s,a,n);c==="active"?o.active_lock_count+=1:c==="expired"?o.stale_lock_count+=1:o.unparseable_lock_count+=1}return o}import lh from"node:path";import $o from"node:fs/promises";import k0 from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function CR(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function Cr(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function _n(e,t){let n=CR(t),r=Cr(e);return r.startsWith(n)?r:`${n}${r}`}import Ce from"node:fs/promises";import ie from"node:path";import{createHash as $R,randomUUID as Pg}from"node:crypto";import Yn from"node:fs/promises";import Sg from"node:path";import{randomUUID as OR}from"node:crypto";import{createRequire as RR}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="97cfeab2-8e3f-5b70-9f64-10494158d141")}catch{}})();var NR="metadata-query-index.sqlite",xg="4";function DR(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Fs;function PR(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?DR(t):null}function Tg(){return Fs!==void 0||(Fs=PR(process.versions.node,RR(import.meta.url))),Fs}function td(e){return Sg.join(e,"runtime",NR)}function LR(e){e.exec(`
|
|
35
43
|
PRAGMA foreign_keys = ON;
|
|
36
44
|
PRAGMA journal_mode = OFF;
|
|
37
45
|
PRAGMA synchronous = OFF;
|
|
@@ -86,7 +94,7 @@ ${i}
|
|
|
86
94
|
tags,
|
|
87
95
|
tokenize = 'unicode61'
|
|
88
96
|
);
|
|
89
|
-
`)}function
|
|
97
|
+
`)}function js(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function Ag(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
|
|
90
98
|
id, relative_path, metadata_json, status, type, priority,
|
|
91
99
|
updated_at, created_at, parent, assignee, sprint, release
|
|
92
100
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -101,13 +109,12 @@ ${i}
|
|
|
101
109
|
parent = excluded.parent,
|
|
102
110
|
assignee = excluded.assignee,
|
|
103
111
|
sprint = excluded.sprint,
|
|
104
|
-
release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE id = ?").run(n.id),e.prepare("INSERT INTO item_search(id, title, description, tags) VALUES (?, ?, ?, ?)").run(n.id,n.title,n.description,n.tags.join(" "));let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function Eu(e){let t=aa(e.pmRoot),n=wu();if(!n){await Kt.rm(t,{force:!0});return}await Kt.mkdir(yu.dirname(t),{recursive:!0});let r=`${t}.${Mk()}.tmp`,o;try{o=new n(r),zk(o),o.exec("BEGIN IMMEDIATE"),Lo(o,"version",bu),Lo(o,"context_fingerprint",e.contextFingerprint),Lo(o,"source_cursor",e.sourceCursor);for(let i of e.rows)vu(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Kt.rm(t,{force:!0}),await Kt.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Kt.rm(r,{force:!0})]),i}}function qk(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function ku(e){let t=aa(e.pmRoot),n;try{await Kt.access(t);let r=wu();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=qk(n);if(o.version!==bu||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return n.close(),!1;n.exec("BEGIN IMMEDIATE");let i=n.prepare("DELETE FROM items WHERE relative_path = ?"),s=n.prepare("SELECT id FROM items WHERE relative_path = ?"),a=n.prepare("DELETE FROM item_search WHERE id = ?");for(let c of e.deletedRelativePaths??[]){let l=s.get(c);i.run(c),l&&a.run(l.id)}return e.row&&vu(n,e.row),Lo(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function Mo(e){await Kt.rm(aa(e),{force:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var Ye=8,Iu=500,Gk="metadata-derived-index",Hk="metadata-cache.json",Vk="metadata-cache-bodies.json",Wk="metadata-cache-collections.json",Kk="metadata-cache-delta.json",Yk="metadata-cache-manifest.json",Tu=4,Xk=["comments","notes","learnings","files","tests","test_runs","docs"];function Ou(){return nt(Y())}function $o(e){let t={...e},n={};for(let r of Xk)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Ru(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function Nu(e,t,n,r){let o=Bk("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function jo(e){return G.join(e,"runtime",Hk)}function Uo(e){return G.join(e,"runtime",Vk)}function zo(e){return G.join(e,"runtime",Wk)}function da(e){return G.join(e,"runtime",Kk)}function ua(e){return G.join(e,"runtime",Yk)}function qo(e,t){let n=G.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var Jk=24,Re=new Map,Bo=new WeakMap;function fa(e){return Bo.get(e)??e.source_cursor}function Zk(e,t){let n=fa(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Bo.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function Qk(e,t){if(!e)return;let n=fa(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Bo.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function eT(e,t){if(!e)return;let n=fa(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Bo.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function tT(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(Zk(e,r),Qk(t,r),eT(n,r))}function ca(e,t){Re.size>=Jk&&!Re.has(e)&&Qt(Re),Re.set(e,t)}async function St(e,t){let n;try{n=await pe.stat(e)}catch{return Re.delete(e),null}let r=Re.get(e);if(r&&tr(r.signature,n.mtimeMs,n.ctimeMs,n.size))return Re.delete(e),Re.set(e,r),r.envelope;let o;try{o=t(await pe.readFile(e,"utf8"))}catch{o=null}return ca(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function nT(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==Ye||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=jo(e),i=await St(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await St(qo(o,t),r);return s===null&&or(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function rT(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Uo(e),o=await St(r,n);return t&&o?.context_fingerprint!==t?await St(qo(r,t),n):o}async function oT(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=zo(e),o=await St(r,n);return t&&o?.context_fingerprint!==t?await St(qo(r,t),n):o}async function Du(e){let t=da(e),n=await St(t,r=>{let o=JSON.parse(r);return o.version!==Ye||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await pe.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function Pu(e){let t=ua(e),n=await St(t,r=>{let o=JSON.parse(r);return o.version!==Ye||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await pe.stat(t),await nr(e)}catch{}return null}async function rr(e,t){await pe.mkdir(G.dirname(e),{recursive:!0}),await j(e,JSON.stringify(t));try{let r=await pe.stat(e);ca(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{Re.delete(e)}let n=G.dirname(G.dirname(e));if(e===jo(n)||e===Uo(n)||e===zo(n)){let r=qo(e,t.context_fingerprint);await j(r,JSON.stringify(t));try{let c=await pe.stat(r);ca(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{Re.delete(r)}let o=G.dirname(e),i=G.extname(e),s=G.basename(e,i),a=(await pe.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==G.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>G.join(o,c.name));if(a.length>Tu){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await pe.stat(l)).mtimeMs}}catch{return null}}))).filter(l=>l!==null);for(let l of c.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,c.length-Tu)))await pe.rm(l.path,{force:!0}),Re.delete(l.path)}}}function iT(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Lu(e,t,n){return e===void 0||iT(e,t,n)}function or(e,t){e&&!e.includes(t)&&e.push(t)}function tr(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function sT(e,t,n){let r=G.join(e,t);try{let o=await pe.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!H(o)&&or(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function aT(e,t){try{let n=await pe.stat(G.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function la(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await aT(e,n))))}function Fo(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&tr(o,r.mtime_ms,r.ctime_ms,r.size)})}function cT(e){return cn.some(t=>e.toLowerCase().endsWith(t))}function lT(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function dT(e,t,n){if(n)for(let r of await Me({path:e,scope:"project"}))or(t,r)}function Su(e,t,n,r){if(e)return t&&n?n.collections:r}async function uT(e,t,n){let r=await pe.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Kr(e);await dT(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&tr(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&tr(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&tr(f,o,i,s);if(!(!l||n.includeBody&&!u||n.includeCollections&&!p))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Su(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let y=await pe.readFile(e,"utf8"),b=Ce(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:v=>or(n.warnings,v)}),E=$o(b.metadata);return lT(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:E.light,heavyMetadata:Su(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function fT(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?Ru(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};Lu(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function pT(e,t,n,r){try{let o=await uT(t,n,r);fT(t,n,r,o)}catch{or(r.warnings,`item_list_item_read_failed:${e}/${G.basename(t)}`)}}function mT(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function _T(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function gT(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function hT(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function yT(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!cT(s))continue;let a=G.join(o,s),c=G.relative(t.pmRoot,a);n.push(pT(r,a,c,t))}return n}async function bT(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Fo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await rr(jo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await rr(ua(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let n=[...e.state.documentsById.values()].map(({candidate:r})=>({relativePath:G.relative(e.pmRoot,r.item_path),metadata:$o(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Eu({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Mo(e.pmRoot)}catch{}}async function wT(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await rr(Uo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function vT(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await rr(zo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function pa(e,t,n={}){let r=await Pu(e);return n.required!==!0&&(r===null||r.entry_count<Iu)?async()=>{}:$e(e,Gk,30,t,!1,!1,3e3)}function Au(e,t){let n=G.relative(e,t);return n===""||n===".."||n.startsWith(`..${G.sep}`)||G.isAbsolute(n)?null:n}async function nr(e){await Promise.all([jo(e),Uo(e),zo(e),da(e),ua(e)].map(async t=>{await pe.rm(t,{force:!0}),Re.delete(t)})),await Mo(e)}async function ET(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await pe.stat(e.mutation.itemPath),n=$o(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function kT(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function ma(e){let t=Au(e.pmRoot,e.itemPath),n=e.previousItemPath?Au(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await nr(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=Nu(e.preferredFormat,e.typeToFolder,e.schema,Ou()),o=await Pu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await Du(e.pmRoot);if(s.invalid)return await nr(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=kT(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await ET({mutation:e});let l=Cu();return await rr(da(e.pmRoot),{version:Ye,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await la(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await ku({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:$o(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Mo(e.pmRoot),[]}catch{return await nr(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function TT(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function xu(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function ST(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function AT(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Kr(n);if(!o)continue;let i=e.includeCollections?Ru(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Lu(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:G.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function xT(e){return e.forceSourceScan||Qr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Fo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||xu(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||xu(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ST(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Go(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Ou(),l=Nu(t,n,o,c),d=await Du(e);d.invalid&&await nr(e);let u=await nT(e,l,i.cacheDiagnostics),f=s?await rT(e,l):null,p=a?await oT(e,l):null;tT(u,f,p,d.envelope);let _=mT(u,l),y=_T(f,l),b=gT(p,l),E=[...new Set(Object.values(n))],v=await la(e,E),C=Object.keys(_),k=Math.max(1,Math.floor(i.derivedIndexMinimumItems??Iu));if(xT({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:v,entryKeys:C,minimumIndexedItems:k,includeBody:s,includeCollections:a,previousBodies:y,previousCollections:b}))return AT({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:y,previousCollections:b});let S=await Promise.all(E.map(K=>sT(e,K,r))),P=Qr(),M=hT(),L={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:P,previousEntries:_,previousBodies:y,previousCollections:b,state:M};await Promise.all(yT(S,L));let W=await la(e,E),J=Fo(v,W)?W:{},O=M.misses.metadata||Object.keys(_).length!==Object.keys(M.newEntries).length||!Fo(u?.directory_signatures,J)||u===null?Cu():u.source_cursor;return await bT({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingCache:u,previousEntries:_,directorySignatures:J,state:M,minimumIndexedItems:k}),s&&await wT({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingBodyCache:f,previousBodies:y,state:M}),a&&await vT({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingCollectionsCache:p,previousCollections:b,state:M}),TT(M)}async function Mu(e,t,n,r,o){return(await Go(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function IT(e){try{return await ir.access(e),!0}catch{return!1}}function OT(e,t){e&&(e.includes(t)||e.push(t))}function RT(e){return e??nt(Y())}function NT(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ue(e,t,n="pm-",r,o=Ae){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=Tt(t,n),c=_n(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=NT(r);for(let f of l)for(let[p]of d)for(let _ of u){let y=ln(e,p,f,_,o);if(await IT(y))return{id:f,type:p,itemPath:y,item_format:_}}return null}async function Ne(e,t={}){let n=await ir.readFile(e.itemPath,"utf8");await Me({path:e.itemPath,scope:"project"});let r=Ce(n,{format:e.item_format,schema:t.schema,extensionFieldNames:RT(t.extensionFieldNames),onWarning:o=>OT(t.warnings,o)});return{raw:n,document:r}}async function sr(e,t,n=Ae,r,o){return await Zn(e),(await Mu(e,t,n,r,o)).map(s=>s.metadata)}async function Ho(e,t,n=Ae,r,o,i={}){return await Zn(e),(await Go(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function Fu(e){return{async get(t){let n=await Ue(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Ne(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>sr(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function DT(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await ir.readdir(CT.join(e,o));for(let s of i)for(let a of cn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function PT(e,t,n,r){let o=Tt(t,n),i=await DT(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Mt(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function $u(e,t,n,r){let o=await PT(e,t,n,r),i=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return o.length>0&&i.unshift(`Did you mean one of: ${o.join(", ")}?`),new h(`Item ${t} not found`,g.NOT_FOUND,{nextSteps:i})}function LT(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function MT(e){let t=e.typeToFolder??ue(e.settings,Y()).type_to_folder,n=await Ue(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await $u(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await $e(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let o=[],{raw:i,document:s}=await Ne(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=ds(e.author),d=Vt(e.settings);if(a&&c!==l&&!e.force&&!LT(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new h(`Item ${n.id} is assigned to ${a}. Use --force to override.`,g.CONFLICT);d.ownership_enforcement==="warn"&&o.push(`ownership_warning:assignee_conflict:${n.id}:${a}`)}return{typeToFolder:t,located:n,originalRaw:i,document:s,warnings:o,releaseLock:r}}catch(o){throw await r(),o}}function FT(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function $T(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await j(e.originalItemPath,e.originalRaw),await ir.rm(e.effectiveTargetItemPath,{force:!0});return}await j(e.originalItemPath,e.originalRaw)}}async function jT(e){let t=await MT({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a}=t;try{let c=we(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=we(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=await e.mutate(l);if(e.skipNoop===!0&&d.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...d.warnings??[]]};let u=e.resolveHistoryContext?.();l.metadata.updated_at=q();let f=we(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Yi({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:Fu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await sa({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",y=Pt(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=ln(e.pmRoot,f.metadata.type,r.id,_,n),E=Be(e.pmRoot,r.id),v=await Ge("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:b,history_path:E,item_format:_,before:c,after:f,contents:y}),{effectiveTargetItemPath:C,effectiveSerializedAfter:k,skipItemWrite:S}=FT(v,b,y),P=await pa(e.pmRoot,e.author),M=[];try{S||await j(C,k),!S&&C!==r.itemPath&&await ir.rm(r.itemPath);let W=zn({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await go(E,W)}catch(J){throw await $T({skipItemWrite:S,effectiveTargetItemPath:C,originalItemPath:r.itemPath,originalRaw:o}),J}S||(M=await ma({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:C,previousItemPath:r.itemPath,document:f}))}finally{await P()}let L=[...await Ee({path:C,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await Ee({path:E,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields})];return Ki({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:Zr(c.metadata,d.changedFields),current:Zr(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...v.warnings,...M,...L]}}finally{await a()}}async function Vo(e){return jT(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function zT(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Vt(e.settings);if(n.ownership_enforcement==="strict")throw new h(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function qT(e){let t=await Q(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new h(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await Ue(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await Ne(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new h(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function ju(e){let t=e.writeHistoryRaw??j;try{await t(e.historyPath,e.nextHistoryRaw),await et(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await UT.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await et(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function _a(e){let t=[...zT({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await $e(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await qT({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}import ar from"node:fs/promises";import{createHash as BT}from"node:crypto";import zu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c6c65ef-115b-50e2-815e-84f6e91158cd")}catch{}})();var qu=9,GT="history-drift-cache.json";function Bu(e){return zu.join(e,"runtime",GT)}async function HT(e){try{let t=await ar.readFile(Bu(e),"utf8"),n=JSON.parse(t);return n.version!==qu||n.history_item_hash_version!==Ve||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Ie.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Ie.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function VT(e,t,n,r,o){let i=Eo(e),s;try{s=await ar.stat(i)}catch(l){return H(l)||o.unreadableStreams.push(fe),!1}let a=o.missingStreams.length,c=await Gu({itemId:fe,historyPath:i,stat:s,cached:t[fe],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.versionSkew&&o.versionSkews.push(fe),c.verification.chainOk||o.chainMismatches.push(fe),n[fe]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function WT(e){return BT("sha256").update(e).digest("hex")}async function KT(e){let t=await ar.readFile(e,"utf8"),n=WT(t);if(t.trim().length===0)return null;let r=[],o=null;for(let u of t.split(/\r?\n/)){let f=u.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),o=p.after_hash}if(!o)return null;let i=Ut(r),s=r.some(u=>u.item_hash_version!==void 0&&!Ie.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,l=c!==void 0&&Ie.includes(c),d=l?c:i.item_hash_version;return{latestAfterHash:o,chainOk:i.ok,versionSkew:s,latestHashComparable:d!==void 0&&(!s||l||c===void 0),contentHash:n,itemHashVersion:d??Ve}}function YT(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Uu(e,t,n){try{let r=await KT(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Gu(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(YT(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Uu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await Uu(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Ie.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function XT(e,t,n,r){let o=Be(e,t.id),i;try{i=await ar.stat(o)}catch(d){return(H(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Gu({itemId:t.id,historyPath:o,stat:i,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&(_o({metadata:c,body:a},s.verification.itemHashVersion).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function JT(e,t){if(!(t.unreadableStreams.includes(fe)||t.chainMismatches.includes(fe)||t.versionSkews.includes(fe)))try{let n=await Gs(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(fe)}}async function Wo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await HT(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await XT(e,f,l,r)&&(a=!0);let d=await VT(e,i,s,c,r);if(a||=d,await JT(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=Bu(e);try{await ar.mkdir(zu.dirname(f),{recursive:!0}),await j(f,JSON.stringify({version:qu,history_item_hash_version:Ve,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[fe]:[]])].sort((f,p)=>f.localeCompare(p));return{...r,driftedItems:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47c087c2-124a-58b7-a5c9-09403235f4a2")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05b945f2-4f96-5f88-98ff-84cc856d0d57")}catch{}})();async function Hu(e,t,n,r){let o=await Ue(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Be(e,o.id),located:o};let i=Tt(t,n.id_prefix),s=_n(t),a=i===s?[i]:[i,s];for(let c of a){let l=Be(e,c);if(await B(l))return{id:c,historyPath:l,located:null}}throw new h(`Item ${t} not found`,g.NOT_FOUND)}import Vu from"node:fs/promises";import Wu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var QT=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function cr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ku(e){return QT.find(t=>t.matches(e))?.kind}function Yu(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=cr(i.agent_provenance)?i.agent_provenance:void 0;if(s===void 0)return i;let a={},c=!1;for(let[d,u]of Object.entries(s)){let f=cr(u)?Ku(u.value):void 0;if(f===void 0){a[d]=u;continue}c=!0,r+=1;let p=i.agent_harness??"unknown",_=`${p}\0${d}\0${f}`,y=t.get(_)??{harness:p,dimension:d,kind:f,count:0};y.count+=1,t.set(_,y)}if(!c)return i;n+=1;let l={...i};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,l}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension)||i.kind.localeCompare(s.kind))}}}async function Xu(e){let t=[];for(let n of await eS(e))try{let r=await Vu.readFile(Wu.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
105
|
-
`)){if(o.trim().length===0)continue;let i=tS(o);if(i===null||!cr(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>cr(a)&&Ku(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function eS(e){try{return(await Vu.readdir(Wu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function tS(e){try{let t=JSON.parse(e);return cr(t)?t:null}catch{return null}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151e5d26-d6f5-5fcf-84ab-ce89e2b7664e")}catch{}})();function Ju(e,t){return t==="body"?e.body:e.metadata[t]}function ga(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(o=>{let i=t.findIndex((s,a)=>!r.has(a)&&ga(o,s));return i<0?!1:(r.add(i),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,o])=>Object.hasOwn(n,r)&&ga(o,n[r]))}function Zu(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let i=e[o],s=new Set;for(let c of Gn(i.patch))s.add(er(c.path)),c.from&&s.add(er(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:o+1,ts:i.ts,author:i.author,op:i.op,fields:a.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function rS(e,t,n){let r=ef.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(er(_.path));let i=new Set([...o].filter(_=>ga(Ju(t,_),Ju(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=Zu(e,s),c=Zu(e,i),l=[...o].sort((_,y)=>_.localeCompare(y)),d=[...s].sort((_,y)=>_.localeCompare(y)),u=[...i].sort((_,y)=>_.localeCompare(y)),f=[...new Set(a.map(_=>_.author))].sort((_,y)=>_.localeCompare(y)),p=[...new Set(c.map(_=>_.author))].sort((_,y)=>_.localeCompare(y));return{reconciled_field_count:o.size,reconciled_fields:l,reverted_field_count:s.size,reverted_fields:d,discarded_events:a,discarded_authors:f,preserved_field_count:i.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function oS(e){try{return await Qu(e)}catch{return null}}async function iS(e){if(await oS(nS.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let o=Object.keys(r).sort();if(n.length!==o.length||n.some((a,c)=>a!==o[c]))return null;let i=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:i[a];return r[a]===se(R(c))})?{receipt:e.receipt,declaredFields:n}:null}async function sS(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Qu(e.itemPath),r=[];for(let s of t){let a=await iS({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let o=new Set(r.flatMap(({declaredFields:s})=>s)),i=e.reconciliation?.reconciled_fields;return r.length>0&&(i===void 0||i.length>0&&i.every(s=>o.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function aS(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await tt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],o=e.options.mergeReceiptProof?await sS({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(o&&!o.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new h(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${o.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=o?.trusted?r.filter(s=>o.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:o,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(We)}}:e.options.auditContext}}async function cS(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Ne(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=vs(i.document),a=n[n.length-1].after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:yt(s,r).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function lS(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function dS(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=yt(e.finalReplay,e.itemHashVersion),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,i=r.indexOf(o),s=yt(n,e.itemHashVersion);return t.push({ts:q(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?ef.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[i],after_hash:s[i],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function uS(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function fS(e){return _a({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>ju({historyPath:e.historyPath,nextHistoryRaw:bt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>Ee({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function ha(e,t,n){let r=re(process.cwd(),n.path);await Oe(r);let o=await te(r),i=ue(o,Y()),s=await Hu(r,e,o,i.type_to_folder);if(!await B(s.historyPath))throw new h(`No history stream exists for ${s.id}.`,g.NOT_FOUND);let a=await Q(s.historyPath),c=await _t(s.historyPath,s.id);if(c.length===0)throw new h(`No history entries exist for ${s.id}; nothing to repair.`,g.USAGE);let l=zt(c),d=Ut(c),u=t.normalizeProvenance?Yu(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Es(u.entries),p=new Set(u.entries.map(ze=>ze.item_hash_version).filter(ze=>ze!==void 0)),_=ho(u.entries,f),y=await cS(s,o,c,f),b=_.finalDocument,E=yt(b,f),v=!1;if(y.currentItemReplay!==null){let ze=yt(y.currentItemReplay,f);v=!E.some((ct,kn)=>ct===ze[kn])}let C=v&&y.currentItemReplay?rS(_.entries,b,y.currentItemReplay):void 0,{mergeReceiptProof:k,effectiveAuditContext:S}=await aS({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:y,reconciliation:C}),P=[_.entriesRehashed>0,_.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),M=Fe(t.author,o.author_default),L=!!t.dryRun,W=lS({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:J,auditEntryAdded:ae}=dS({reanchorEntries:_.entries,changed:P,reconcileNeeded:v,currentItemReplay:y.currentItemReplay,finalReplay:b,author:M,message:W,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...S,provenance_normalization:u.receipt}:S,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),O=zt(J);if(!O.ok)throw new h(`history-repair produced an invalid rewritten chain (${O.errors.join(", ")}).`,g.GENERIC_FAILURE);let K=uS(P,_.skippedOps,C);return P&&!L&&K.push(...await fS({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:M,force:t.force,loadedItem:y.loadedItem,historyPath:s.historyPath,rewrittenEntries:J})),{id:s.id,dry_run:L,changed:P,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!l.ok,entries_rehashed:_.entriesRehashed,entries_patch_repaired:_.entriesPatchRepaired,converted_replace_to_add:_.convertedReplaceToAdd,skipped_ops:_.skippedOps,reconciled_with_item:v,audit_entry_added:ae,verify_ok:O.ok,verify_errors:O.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...C?{reconciliation:C}:{},...k?{merge_receipt_proof:k}:{},warnings:[...new Set(K)].sort((ze,ct)=>ze.localeCompare(ct)),generated_at:q()}}async function tf(e,t){let n=re(process.cwd(),t.path);await Oe(n);let r=await te(n),o=ue(r,Y()),i=[],s=await Ho(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await Wo(n,s),c=e.normalizeProvenance?await Xu(n):[],l=[...new Set([...a.driftedItems,...c])].sort((p,_)=>p.localeCompare(_)),d=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let p of l)try{let _=await ha(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),y=_.changed?"repaired":"skipped_clean";f[y]+=1,u.push(..._.warnings.map(b=>`${p}:${b}`)),d.push({id:p,outcome:y,entries_rehashed:_.history.entries_rehashed,entries_patch_repaired:_.history.entries_patch_repaired,reconciled_with_item:_.history.reconciled_with_item,..._.reconciliation?{reconciliation:_.reconciliation}:{},..._.merge_receipt_proof?{merge_receipt_proof:_.merge_receipt_proof}:{},warnings:_.warnings})}catch(_){f.failed+=1,d.push({id:p,outcome:"failed",error:_ instanceof Error?_.message:String(_)})}return e.dryRun||await ys(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:f,warnings:[...new Set([...i,...u])].sort((p,_)=>p.localeCompare(_)),generated_at:q()}}import pc from"node:fs/promises";import{realpathSync as nI}from"node:fs";import{execFile as rI}from"node:child_process";import he from"node:path";import{promisify as oI}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a69725-363a-59e1-96c6-1e1ca079a311")}catch{}})();var pS=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm health --check-only --full --json",summary:"One or more append-only history coordinates reference receipt evidence that is no longer present; inspect the bounded item, line, and privacy-safe receipt locator, then recover the named evidence from an authoritative clone or backup without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function mS(e){if(typeof e!="string")return;let t=e.trim();for(let n of pS)if(t===n.code||t.startsWith(`${n.code}:`))return n}function _S(e){let t={};for(let n of e){let r=mS(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function nf(e){return Object.values(_S(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var gS=["metadata","resolution"],ya=["metadata","resolution","estimates","lifecycle"],hS="completed";function ba(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rf(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function of(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=rf(n.close_reason)??hS;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ba(r)}`,gate:"resolution"})}return t}function sf(e){let t=[];for(let n of e){let r=rf(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${ba(r)}`,gate:"metadata"})}return t}function af(e,t){return e.map(n=>{let r=Yd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function cf(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function lf(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${ba(n.path)}`})}return t}function df(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new h(`--fix-scope values must not be empty. Supported values: ${ya.join(", ")}.`,g.USAGE);return new Set(gS)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(ya.includes(o)){n.add(o);continue}throw new h(`Unknown --fix-scope value "${r}". Supported values: ${ya.join(", ")}.`,g.USAGE)}return n}function uf(e,t){let n=[],r=[];for(let o of e)o.gate!==void 0&&!t.has(o.gate)?r.push(o):n.push(o);return{applicable:n,gated:r}}function lr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var yS=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function bS(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=yS.exec(n);if(!r)return null;let o=r[1],i=o.toUpperCase(),s=o.slice(0,o.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(o.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${i}`)||l.includes(`ISSUE CODE \`${i}\``)||l.includes(`\`${i}\``)||l.includes(`[${i}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?i:null}function ff(e){return typeof e=="string"&&e.trim().length>0}function pf(e,t={}){let n=new Map;for(let o of e){if(typeof o.title!="string"||ff(o.duplicate_of))continue;let i=bS(o.title,{...t,evidenceText:o.body});if(i===null)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(a=>a.id===o.id)||s.push({id:o.id,title:o.title,parent:ff(o.parent)?o.parent.trim():null})}let r=[];for(let[o,i]of n){if(i.length<2)continue;let s=new Set(i.map(l=>l.id.toLowerCase())),a=i.filter(l=>l.parent===null||!s.has(l.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((l,d)=>l.id.localeCompare(d.id));r.push({code:o,count:c.length,ids:c.map(l=>l.id),titles:c.map(l=>l.title)})}return r.sort((o,i)=>o.code.localeCompare(i.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function mf(e){let t=new Map;for(let r of e){let o=t.get(r.item_type);o||(o=new Map,t.set(r.item_type,o)),o.set(r.field,(o.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r),i={};for(let s of[...o.keys()].sort((a,c)=>a.localeCompare(c)))i[s]=o.get(s);n[r]=i}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var _f=3;function gf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function hf(e,t,n=_f){let r=Number.isFinite(n)&&n>=1?Math.floor(n):_f,o=new Map;for(let i of t){let s=gf(i);if(s.length===0)continue;let a=o.get(s);a?a.push(i):o.set(s,[i])}return e.map(i=>{let s=(o.get(gf(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function yf(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var wS=/^[a-z][a-z0-9+.-]+:\/\//i;function dr(e){return wS.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function vS(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function bf(e){return`${e.item_id} ${e.link_kind}`}function wf(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=vS(o.classification,r.classification),o.owners.set(bf(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[bf(r),r]])})}return[...n.entries()].sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({path:r,classification:o.classification,items:[...o.owners.values()].map(i=>{let s=t(i.item_id);return{id:i.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:i.link_kind}}).sort((i,s)=>{let a=i.id.localeCompare(s.id);return a!==0?a:i.field.localeCompare(s.field)})}))}function ES(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function vf(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${ES(r.title)}"`);return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="971d929f-12be-5648-93c9-8a9878b40dde")}catch{}})();function Ko(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function ur(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3f3beb2-1d60-52fe-88ce-1ab3cb9dba0d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d49d73c9-f988-5c3c-a22d-0580ee5526f6")}catch{}})();function Yt(){let e=dn();for(let t of Y()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="924f7718-0527-5967-8ab0-53e8228bd665")}catch{}})();function Xo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Yo(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function kS(e,t){let n=new Set,r=[];for(let o of[...e].sort()){if(n.has(o))continue;n.add(o);let i=[{nodeId:o,children:[...t.get(o)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),i.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),i.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function TS(e,t){let n=[...e].sort(),r=kS(n,t),o=new Set,i=SS(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=AS(a,i,o);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function SS(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,o]of t)for(let i of o)n.get(i)?.add(r);return n}function AS(e,t,n){let r=[],o=[e];for(n.add(e);o.length>0;){let i=o.pop();r.push(i);for(let s of[...t.get(i)].sort())n.has(s)||(n.add(s),o.push(s))}return r.sort()}function xS(e){let t=new Map;for(let n of e){let r=Xo(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function CS(e,t,n){let r=Xo(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function IS(e,t,n,r){let o=Xo(t?.id),i=r.resolve(t?.kind);if(!o||!n.has(o)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:o,child_id:s?o:e,source:"dependency",kind:i.kind,holder_id:e,target_id:o,child_cardinality:s?i.incoming:i.outgoing}}function OS(e,t){let n=new Map;for(let[r,o]of e){let i=CS(r,o,e);i&&n.set(Yo(i),i);for(let s of o.dependencies??[]){let a=IS(r,s,e,t);a&&n.set(Yo(a),a)}}return[...n.values()].sort((r,o)=>Yo(r).localeCompare(Yo(o)))}function RS(e,t,n){let r=new Set(e.filter(o=>o.child_cardinality==="one").map(o=>o.child_id));return[...t].filter(([o,i])=>i.length>1&&r.has(o)).map(([o,i])=>({child_id:o,parent_ids:[...i],legacy_terminal:n.has(o)&&i.every(s=>n.has(s))})).sort((o,i)=>o.child_id.localeCompare(i.child_id))}function NS(e,t,n){let r=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=r.get(i.child_id)??new Set;s.add(i.parent_id),r.set(i.child_id,s)}let o=[];for(let[i,s]of e){let a=Xo(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(i)??[]].filter(l=>l!==a).sort();c.length!==0&&o.push({child_id:i,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(i)&&n.has(a)&&c.every(l=>n.has(l))})}return o.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function wa(e,t=r=>r==="closed"||r==="canceled",n=Yt()){let r=xS(e),o=OS(r,n),i=DS(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=TS([...r.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:o,cycles:a,cardinality_violations:RS(o,i.parents_by_child,s),divergences:NS(r,o,s)}}function DS(e){let t=new Map,n=new Map;for(let r of e){let o=t.get(r.child_id)??new Set;o.add(r.parent_id),t.set(r.child_id,o);let i=n.get(r.parent_id)??new Set;i.add(r.child_id),n.set(r.parent_id,i)}return{parents_by_child:new Map([...t].map(([r,o])=>[r,[...o].sort()])),children_by_parent:new Map([...n].map(([r,o])=>[r,[...o].sort()]))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e04a91fa-4625-50fd-9bfd-c712126baf0d")}catch{}})();function Ef(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function PS(e,t,n=!0){let r=Ef(e);return n&&(ur(t)||r!==void 0&&Ko(r))}function kf(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),o=new Map,i=(c,l,d,u,f)=>{let p=Ef(l);if(!p||r.has(p.toLowerCase())||PS(p,void 0,f))return;let _={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};o.set(`${_.holder_id}::${_.target_id}::${_.kind}::${_.source}`,_)};for(let c of n){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;ur(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...o.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}import gn from"node:fs/promises";import hn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function LS(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await gn.readdir(hn.join(e,o))}catch{return}for(let s of i)for(let a of cn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${o}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((o,i)=>o.relativePath.localeCompare(i.relativePath))}function MS(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Le(t);if(s){i.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{i.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&o.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function va(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function FS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await gn.readdir(hn.join(e,"history"))}catch{return n}for(let o of r.sort((i,s)=>i.localeCompare(s))){if(!o.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await gn.readFile(hn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:va("history stream",s)});continue}MS({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function Tf(e){let t=Le(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function $S(e){let t=[],n=0,r=null;try{r=await Q(ve(e))}catch(i){n+=1,t.push({path:"settings.json",detail:va("configuration file",i)})}if(r!==null){n+=1;let i=Tf(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await gn.readdir(hn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of o.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let s;try{s=await gn.readFile(hn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:va("configuration file",c)});continue}let a=Tf(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function Sf(e,t,n,r={}){let o=await LS(e,n),i=new Set(o.map(u=>u.id)),s=new Map;for(let u of o){let f=s.get(u.id);f===void 0?s.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((p,_)=>p.localeCompare(_))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(o.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=hn.join(e,u.relativePath);return Ce(await gn.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await FS(e,i),d=await $S(e);return{item_files_on_disk:o.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import{execFile as jS}from"node:child_process";import{realpath as US}from"node:fs/promises";import Af from"node:path";import{promisify as zS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var qS=zS(jS),BS=32*1024*1024,GS=1e4,HS=["search/eval-queries.json"];function Ea(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function VS(e){return`'${e.replaceAll("'","'\\''")}'`}async function WS(e,t=US){return t(e).catch(()=>Af.resolve(e))}async function xf(e){let t=await kt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await WS(e),r=Ea(Af.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let o=iu.map(i=>`${r}/${Ea(i)}`);try{let{stdout:i}=await qS("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:BS,windowsHide:!0,timeout:GS}),s=new Set(HS.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(Ea(l))))].sort((l,d)=>l.localeCompare(d)),c=o.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>VS(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import tc from"node:fs/promises";import nc from"node:path";import{Option as vW}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var yn="-",If=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function ka(e){return e.replace(/\r\n/g,`
|
|
106
|
-
`)}function Of(e){let t=ka(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
|
|
107
|
-
`);
|
|
108
|
-
`)
|
|
109
|
-
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=ka(t).split(`
|
|
110
|
-
`).map(i=>i.trim()).filter(i=>i.length>0);for(let i of o){let s=i.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(s){let a=s[1].trim();n[a]=Rf(s[3].trim()),r=a;continue}if(r&&If.has(r.toLowerCase())){n[r]=`${n[r]}
|
|
111
|
-
${i}`;continue}return null}return n}function bn(e,t){let n=Of(e).trim();if(!n)throw new h(`${t} cannot be empty`,g.USAGE);let r=JS(n);if(r)return r;let o={},i,s=KS(n);for(let a of s){let c=YS(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new h(Cf(e,t),g.USAGE);let d=Rf(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&If.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new h(Cf(e,t),g.USAGE)}return o}var ZS=/^[A-Za-z]:[\\/]/,QS=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Ta(e){let t=e.trim();return ZS.test(t)?!1:QS.test(t)}function Nf(e,t,n,r){if(!(r||!e.includes(",")))throw new h(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,g.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function wn(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new h(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,g.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new h(`${t} provides key "${i}" more than once after case normalization.`,g.USAGE);e[s]=e[i],delete e[i]}}}async function eA(e){if(process.stdin.isTTY===!0)throw new h(`${e} value "${yn}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,g.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(ka(r))}),process.stdin.on("error",o=>{n(o)})})}function fr(){let e,t,n=async i=>{if(t&&t!==i)throw new h(`Only one option may use "${yn}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);return t=i,e||(e=eA(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==yn?i:await n(s)},resolveList:async(i,s,a=!0)=>{if(!a)return i;if(!i)return;let c=i.map((u,f)=>u.trim()===yn?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new h(`${s} accepts "${yn}" stdin token at most once per command invocation`,g.USAGE);let l=await n(s),d=[...i];return d[c[0]]=l,d}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="411f4336-eb02-5167-9dce-ea99822a8a14")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var tA={critical:0,high:1,medium:2,low:3,minimal:4},nA=Object.keys(tA),Mz=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${nA.join(", ")}), case-insensitive`;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9581c92-5e8a-589d-9681-d4d014e6902b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="989b570c-112e-5ee3-8731-ab34f215ba45")}catch{}})();var Qz=new Map(bi.map(e=>[e.toLowerCase(),e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();import{createRequire as EA}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var kA=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,iB=new RegExp(`\\b(${kA.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var sB=EA(import.meta.url);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var lB=new Map([[g.USAGE,"invalid_command_usage"],[g.NOT_FOUND,"item_not_found"],[g.CONFLICT,"lock_conflict"],[g.DEPENDENCY_FAILED,"dependency_failed"]]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e6ba316-b067-51df-abeb-c3e3488a504d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var SA=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],bB=new Map(SA.map(e=>[e.action,e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ad30a32-0f83-5473-b0a3-349e271d8378")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dff9b113-2b29-5154-afbf-f191f2f556a6")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var xB=Object.freeze({"<":"<",">":">",""":'"',"'":"'","&":"&"});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4ecab833-db06-5baa-bfe6-d28b4c97f85a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();import UB from"node:readline/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();import CA from"node:crypto";import Sa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var tG=Sa.join("runtime","telemetry","events.jsonl"),nG=Sa.join("runtime","telemetry","state.json"),rG=Sa.join("runtime","telemetry","otel-spans.jsonl");var oG=3600*1e3;var iG=globalThis.fetch,IA=["user","automation","test","dogfood"],sG=Promise.resolve(),aG=Promise.resolve();var cG=new Set(IA);var lG=CA.randomUUID();var jf="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",dG=new RegExp(`\\b(${jf})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),uG=new RegExp(`(--${jf})(=|\\s+)([^\\s,;]+)`,"giu");(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d45775e5-6826-521b-80b3-429ed22947d9")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f56c4ef-58e1-5cf6-a10e-dfa29b9ad3e8")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be7e506f-c48f-5dfb-9fed-ba1e74fa60ff")}catch{}})();var Aa=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or pass title as the first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit item id (normalized with the configured id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Item type (built-ins plus any configured custom types)"},{target:"template",keys:["template"],option:"--template <value>",description:"Apply named create template defaults before explicit flags"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Create required-option policy mode: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Scheduling preset for Reminder|Meeting|Event: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Close reason when creating directly in a terminal status",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for a terminal imported item",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],Uf=Aa.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),zf=Aa.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),xa=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by dependency id or exact row signature (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append linked test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0}],Ca=xa.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),qf=xa.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88009976-e03f-5a67-b6fc-bf60240dde49")}catch{}})();function le(e){return e.map(t=>({...t}))}var Ia=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],Bf=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],UA=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Bf],Gf=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],zA=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],qA=[...Ia,...Gf],Hf=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],BA=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Vf=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],Oa=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...le(Ia),...le(UA),{param:"ids",flag:"--ids"},...le(Gf),...le(BA),...le(Hf),...le(Vf),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],Ra=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...le(qA)],Na=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...le(Ia),...le(Bf),...le(zA),...le(Hf),...le(Vf),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Wf=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],Jo=le(Wf),Kf=[{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],Da=le(Kf),Yf=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],Pa=le(Yf),La=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],Ma=le(La),Fa=le(La);var $a=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],ja=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4efc5934-7d1b-517b-8b5e-eb2fe14379f2")}catch{}})();function T(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Xf(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var z=T("id","item_id",!0),pr=T("id","item_id",!1),mr=T("text","string",!1),_r=T("plan-id","item_id",!0),Jf=T("step","string",!0),HA=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],Ua=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],VA={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},vn=[{command:"plan create",parent:"plan",action:"create",slots:[T("title","string",!1,{polymorphic:!0})],accepted_flags:HA,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[_r],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[_r],accepted_flags:Ua,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(VA).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[_r,Jf],accepted_flags:Ua,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[_r,Jf,T("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(e=>({command:`plan ${e}`,parent:"plan",action:e,slots:[_r],accepted_flags:Ua,description:`${Xf(e)} for one Plan item.`,example:`pm plan ${e} pm-a1b2`})),...["list","show","put","remove"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[T("kind","string",!0),...e==="list"?[]:[T("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Xf(e)} assurance declarations by kind.`,example:e==="list"?"pm assurance list measurement":`pm assurance ${e} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[T("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[T("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[T("preset","string",e==="apply")],accepted_flags:["--author","--message","--owner"],description:e==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:e==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[T("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[T("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[T("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[T("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[T("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],WA=[...vn].sort((e,t)=>t.command.length-e.command.length),KA=new Map([["append",[z,mr]],["assurance",[T("action","action",!0),T("kind","string",!1),T("id","string",!1)]],["beads import",[T("file","string",!1)]],["changelog export",[T("file","string",!1)]],["claim",[pr]],["close",[z,mr]],["close-task",[z,T("reason","string",!1)]],["comments",[z,mr]],["completion",[T("shell","string",!1)]],["config",[T("scope","string",!1,{polymorphic:!0}),T("action","action",!1),T("key","string",!1),T("value","string",!1,{polymorphic:!0})]],["copy",[z]],["create",[T("type-or-title","string",!1,{polymorphic:!0}),T("title","string",!1)]],["delete",[z]],["deps",[z]],["docs",[z]],["event",[T("title","string",!0)]],["files",[z]],["files discover",[z]],["files lookup",[T("paths","string",!0,{variadic:!0})]],["focus",[pr]],["get",[z]],["graph",[T("subcommand","action",!0),pr,T("target","item_id",!1)]],["guide",[T("topic","string",!1)]],["history",[z]],["history-compact",[pr]],["history-redact",[z]],["history-repair",[pr]],["init",[T("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[z,T("reason","string",!1)]],["item reopen",[z,T("reason","string",!0)]],["learnings",[z,mr]],["meet",[T("title","string",!0)]],["merge",[T("subcommand","action",!0),T("artifact","string",!1),T("base","string",!1),T("ours","string",!1),T("theirs","string",!1)]],["notes",[z,mr]],["package",[T("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[T("target","string",!0)]],["package upgrade",[T("target","string",!1)]],["packages",[T("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[T("target","string",!0)]],["packages upgrade",[T("target","string",!1)]],["pause-task",[z]],["plan",[T("subcommand","action",!0),T("id","item_id",!1,{polymorphic:!0}),T("step","string",!1),T("new-order","integer",!1)]],["profile",[T("subcommand","action",!0),T("name","string",!1)]],["release",[z]],["remind",[T("title","string",!0)]],["restore",[z,T("target","string",!0)]],["schema",[T("subcommand","action",!0),T("name","string",!1)]],["search-advanced",[T("keywords","string",!0,{variadic:!0})]],["search",[T("keywords","string",!0,{variadic:!0})]],["start-task",[z]],["telemetry",[T("namespace-or-subcommand","action",!1,{polymorphic:!0}),T("subcommand","action",!1)]],["test",[z]],["update",[z]],["workspace snapshot",[T("action","action",!0),T("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("targets","string",!1,{variadic:!0})]])),["vcs abandon",[z]],["vcs create",[T("title","string",!0)]],["vcs merge",[z]],["vcs propose",[z]],["vcs ref-create",[T("name","string",!0)]],["vcs show",[z]]]);function YA(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function XA(e){let t=YA(e);return WA.find(n=>n.command===t||t.startsWith(`${n.command} `))}function $(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var JA=[...$("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...$("item","item","consolidation","pm-yql1",["append","claim","close","close-many","close-task","comments","copy","create","delete","docs","files","get","learnings","notes","pause-task","release","start-task","test","update","update-many"]),...$("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...$("list","list","target_noun","pm-pfqi",["list"]),...$("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...$("context","context","target_noun","pm-pbyu",["context"]),...$("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...$("search","search","target_noun","pm-pbyu",["search"]),...$("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...$("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...$("graph","graph","target_noun","pm-pbyu",["graph"]),...$("graph","graph show","consolidation","pm-yql1",["deps"]),...$("history","history","target_noun","pm-pbyu",["history"]),...$("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...$("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...$("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...$("workspace","workspace init","consolidation","pm-n7rr",["init"]),...$("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...$("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...$("package","package","package_owned","package:beads",["beads import"]),...$("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...$("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...$("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...$("ops","ops assurance","consolidation","pm-2tan",vn.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...$("plan","plan","target_noun","pm-pbyu",["plan"]),...$("plan","plan","target_noun","pm-2tan",vn.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...$("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...$("help","help","target_noun","pm-pbyu",["help"]),...$("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],ZA=[...new Set(JA.map(({command:e})=>e))].map(e=>({command:e,slots:XA(e)?.slots??KA.get(e)??[]}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function za(e){return[...new Set(Array.from(e,t=>t.trim()).filter(t=>t.length>0))]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="789faf62-dfbf-56ff-9412-55adc5c12d3d")}catch{}})();var Zf=Ui.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),QA=[...Zf,{flag:"--version"}],Qf=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--has-notes"},{flag:"--no-notes"},{flag:"--has-learnings"},{flag:"--no-learnings"},{flag:"--has-files"},{flag:"--no-files"},{flag:"--filter-files-missing"},{flag:"--has-docs"},{flag:"--no-docs"},{flag:"--filter-docs-missing"},{flag:"--has-tests"},{flag:"--no-tests"},{flag:"--has-comments"},{flag:"--no-comments"},{flag:"--has-deps"},{flag:"--no-deps"},{flag:"--has-body"},{flag:"--empty-body"},{flag:"--has-linked-command"},{flag:"--no-linked-command"}],ep=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--filter-has-notes"},{flag:"--filter-no-notes"},{flag:"--filter-has-learnings"},{flag:"--filter-no-learnings"},{flag:"--filter-has-files"},{flag:"--filter-no-files"},{flag:"--filter-has-docs"},{flag:"--filter-no-docs"},{flag:"--filter-has-tests"},{flag:"--filter-no-tests"},{flag:"--filter-has-comments"},{flag:"--filter-no-comments"},{flag:"--filter-has-deps"},{flag:"--filter-no-deps"},{flag:"--filter-has-body"},{flag:"--filter-empty-body"},{flag:"--filter-has-linked-command"},{flag:"--filter-no-linked-command"},{flag:"--ids",list:!0},{flag:"--limit"},{flag:"--offset"}],Qo=Va([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--status",list:!0},{flag:"--all",value_type:"boolean"},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--today"},{flag:"--recent"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--ids",list:!0},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...Qf,{flag:"--limit"},{flag:"--offset"},{flag:"--after"},{flag:"--no-truncate"},{flag:"--compact"},{flag:"--brief"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--sort"},{flag:"--order"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--include-body"},{flag:"--strict-read"},{flag:"--format"},{flag:"--stream"}],new Set(["--limit","--token-budget","--offset","--after","--no-truncate","--compact","--brief","--full","--fields","--include-body","--strict-read"])),tp=[{flag:"--group-by",list:!0},{flag:"--count"},{flag:"--completion"},{flag:"--sum"},{flag:"--avg"},{flag:"--include-unparented"},{flag:"--include_unparented"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0}],np=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body","--text"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function Va(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var rp=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note","--text"]},{flag:"--add-json"},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--since"},{flag:"--event-type"},{flag:"--include-meta"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],op=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning","--text"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ip=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--append-stable"},{flag:"--validate-paths"},{flag:"--scope"},{flag:"--limit"},{flag:"--offset"},{flag:"--no-truncate"},{flag:"--strict-read"},{flag:"--explain"},{flag:"--lines",value_name:"start:end"},{flag:"--decision-depth",value_name:"n",value_type:"number"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],sp=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--validate-paths"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ap=[{flag:"--id",value_name:"item-id"},{flag:"--limit"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--diff"},{flag:"--field"},{flag:"--verify"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--format"}],cp=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],lp=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],dp=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],up=[{flag:"--event",repeatable:!0},{flag:"--all-actionable"},{flag:"--dry-run"},{flag:"--plan-fingerprint"},{flag:"--limit",value_type:"number"},{flag:"--attributed-author",aliases:["--attributed_author"]},{flag:"--reviewer"},{flag:"--reason"}],fp=[{flag:"--id",value_name:"item-id"},{flag:"--before"},{flag:"--ids",list:!0},{flag:"--all-over",value_type:"number"},{flag:"--closed"},{flag:"--all-streams"},{flag:"--min-entries",value_type:"number"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],pp=[{flag:"--description"},{flag:"--default-status",aliases:["--default_status"]},{flag:"--folder"},{flag:"--alias"},{flag:"--role"},{flag:"--order"},{flag:"--type"},{flag:"--commands"},{flag:"--cli-flag"},{flag:"--required"},{flag:"--required-on-create"},{flag:"--no-allow-unset"},{flag:"--required-types"},{flag:"--infer"},{flag:"--min-count"},{flag:"--apply",value_type:"boolean"},{flag:"--to"},{flag:"--migration-id",aliases:["--migration_id"]},{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],mp=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Wa=[{flag:"--title"},{flag:"--description"},{flag:"--scope"},{flag:"--parent"},{flag:"--related"},{flag:"--blocks"},{flag:"--blocked-by",aliases:["--blocked_by"]},{flag:"--harness"},{flag:"--mode"},{flag:"--resume-context",aliases:["--resume_context"]},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--priority"},{flag:"--status",short:"-s"},{flag:"--create-mode",aliases:["--create_mode"]},{flag:"--deadline"},{flag:"--estimate",aliases:["--estimated-minutes","--estimated_minutes"]},{flag:"--acceptance-criteria",aliases:["--acceptance_criteria","--ac"],repeatable:!0},{flag:"--definition-of-ready",aliases:["--definition_of_ready"]},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now",aliases:["--why_now"]},{flag:"--assignee"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-reason",aliases:["--blocked_reason"]},{flag:"--unblock-note",aliases:["--unblock_note"]},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps",aliases:["--repro_steps"]},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--affected-version",aliases:["--affected_version"]},{flag:"--fixed-version",aliases:["--fixed_version"]},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact",aliases:["--customer_impact"]},{flag:"--comment",repeatable:!0},{flag:"--note",repeatable:!0},{flag:"--learning",repeatable:!0},{flag:"--reminder",repeatable:!0},{flag:"--event",repeatable:!0},{flag:"--type-option",aliases:["--type_option"],repeatable:!0},{flag:"--body"},{flag:"--claim"},{flag:"--from-search",aliases:["--from_search"]},{flag:"--template"},{flag:"--step-title",aliases:["--step_title"]},{flag:"--step"},{flag:"--step-body",aliases:["--step_body"]},{flag:"--step-owner",aliases:["--step_owner"]},{flag:"--step-status",aliases:["--step_status"]},{flag:"--step-evidence",aliases:["--step_evidence"]},{flag:"--step-blocked-reason",aliases:["--step_blocked_reason"]},{flag:"--step-replacement",aliases:["--step_replacement"]},{flag:"--depends-on",aliases:["--depends_on"]},{flag:"--link"},{flag:"--link-kind",aliases:["--link_kind"]},{flag:"--link-note",aliases:["--link_note"]},{flag:"--promote-to-item-dep",aliases:["--promote_to_item_dep"]},{flag:"--allow-multiple-active",aliases:["--allow_multiple_active"]},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--decision-text",aliases:["--decision_text","--decision"]},{flag:"--decision-rationale",aliases:["--decision_rationale"]},{flag:"--decision-evidence",aliases:["--decision_evidence"]},{flag:"--discovery-text",aliases:["--discovery_text","--discovery"]},{flag:"--validation-text",aliases:["--validation_text","--validation"]},{flag:"--validation-command",aliases:["--validation_command"]},{flag:"--validation-expected",aliases:["--validation_expected"]},{flag:"--depth"},{flag:"--field"},{flag:"--fields",list:!0},{flag:"--steps"},{flag:"--materialize-type",aliases:["--materialize_type"]},{flag:"--materialize-parent",aliases:["--materialize_parent"]},{flag:"--materialize-tags",aliases:["--materialize_tags"]},{flag:"--author"},{flag:"--message"},{flag:"--force"}],_p=[{flag:"--id-prefix",aliases:["--prefix"]},{flag:"--preset"},{flag:"--type-preset"},{flag:"--defaults",short:"-y",aliases:["--yes"]},{flag:"--author"},{flag:"--agent-guidance"},{flag:"--with-packages"},{flag:"--no-merge-fence"},{flag:"--workspace"},{flag:"--force"},{flag:"--verbose"}],gp=[{flag:"--criterion"},{flag:"--clear-criteria"},{flag:"--format"},{flag:"--policy"},{flag:"--default-depth"},{flag:"--activity-limit"},{flag:"--stale-threshold-days"},{flag:"--section-hierarchy"},{flag:"--section-activity"},{flag:"--section-progress"},{flag:"--section-blockers"},{flag:"--section-files"},{flag:"--section-workload"},{flag:"--section-staleness"},{flag:"--section-tests"}],Ka=[{flag:"--init"},{flag:"--scaffold"},{flag:"--capability"},{flag:"--install"},{flag:"--uninstall"},{flag:"--explore"},{flag:"--list"},{flag:"--manage"},{flag:"--describe"},{flag:"--markdown"},{flag:"--output"},{flag:"--reload"},{flag:"--watch"},{flag:"--doctor"},{flag:"--catalog"},{flag:"--adopt"},{flag:"--adopt-all"},{flag:"--activate"},{flag:"--deactivate"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"},{flag:"--detail"},{flag:"--trace"},{flag:"--runtime-probe"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],it=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],hp=[...it,{flag:"--capability"}],qa=[...Ka,{flag:"--declarative"}],ex=[...hp,{flag:"--declarative"}];var tx=[...it,{flag:"--markdown"},{flag:"--output"}];var nx=[...it,{flag:"--dry-run"}],rx=[...it,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],ox=[...it,{flag:"--watch"}],ix=[...it,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],sx=[...it,{flag:"--fields",list:!0}],ax=[...it,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],yp=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],bp=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var wp=[{flag:"--id",value_name:"item-id"},{flag:"--reason",value_name:"value"},{flag:"--close-reason",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--duplicate-of",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",aliases:["--expected_result","--expected"],value_name:"value"},{flag:"--actual-result",aliases:["--actual_result","--actual"],value_name:"value"},{flag:"--force",value_type:"boolean"}],vp=[{flag:"--filter-status",list:!0},{flag:"--filter-type"},{flag:"--filter-tag"},{flag:"--filter-priority"},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee"},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint"},{flag:"--filter-release"},...ep,{flag:"--reason"},{flag:"--completed-at"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--validate-close"},{flag:"--author"},{flag:"--message"},{flag:"--force"},{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"}],Ep=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],kp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"},{flag:"--if-available"},{flag:"--next"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee-filter"},{flag:"--parent"},{flag:"--sprint"},{flag:"--release"},{flag:"--max-attempts"},{flag:"--include-decisions"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--explain-ranking",aliases:["--explain_ranking"]}],Tp=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Sp=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Ap=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],xp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Cp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Ip=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],Op=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Ya=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...Op],Rp=Ya,Np=[{flag:"--at"},{flag:"--text"},...Op],Dp=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-json"},{flag:"--remove"},{flag:"--remove-index",repeatable:!0},{flag:"--run"},{flag:"--match"},{flag:"--only-index"},{flag:"--only-last"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--acknowledge-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"},{flag:"--measure",list:!0},{flag:"--metric-below"},{flag:"--metric-diff"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Pp=[{flag:"--status"},{flag:"--limit"},{flag:"--offset"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"}],Lp=[{flag:"--limit"}],Mp=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Fp=[{flag:"--dry-run"},{flag:"--scope"}],$p=[{flag:"--include-empty"},{flag:"--storage"},{flag:"--metadata-coverage"},{flag:"--field-utilization"},{flag:"--by-assignee"},{flag:"--by-tag"},{flag:"--by-priority"},{flag:"--tag-prefix"},{flag:"--analytics"}],jp=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],Up=[{flag:"--strict-directories"},{flag:"--require-merge-drivers"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--check-only"},{flag:"--check-telemetry"},{flag:"--no-refresh"},{flag:"--refresh-vectors"},{flag:"--verbose-stale-items"},{flag:"--verbose-author-events"},{flag:"--brief"},{flag:"--summary"},{flag:"--skip-vectors"},{flag:"--skip-integrity"},{flag:"--skip-drift"},{flag:"--full"}],zp=[{flag:"--check-metadata"},{flag:"--metadata-profile"},{flag:"--check-resolution"},{flag:"--check-lifecycle"},{flag:"--check-stale-blockers"},{flag:"--dependency-cycle-severity"},{flag:"--parent-cycle-severity"},{flag:"--check-files"},{flag:"--scan-mode"},{flag:"--include-pm-internals"},{flag:"--verbose-file-lists"},{flag:"--verbose-diagnostics"},{flag:"--all-affected-ids"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--fix-hints"},{flag:"--auto-fix"},{flag:"--dry-run"},{flag:"--fix-scope"},{flag:"--prune-missing"},{flag:"--check-history-drift"},{flag:"--check-command-references"},{flag:"--check-storage-integrity"},{flag:"--counts"},{flag:"--full"}],Xa=[{flag:"--definition",value_name:"json"},{flag:"--trigger",value_name:"value"},{flag:"--tree",value_name:"value"},{flag:"--gate",value_name:"id"},{flag:"--limit",value_name:"number"},{flag:"--dry-run"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--owner",value_name:"item-id"},{flag:"--apply",value_type:"boolean"},{flag:"--enforcement",value_name:"level"}],qp=[{flag:"--assignee"},{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--allow-unresolved-deps"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-by"},{flag:"--blocked-reason"},{flag:"--unblock-note"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--actual-result"},{flag:"--affected-version"},{flag:"--fixed-version"}],Bp=[{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"}],Gp=[{short:"-p",flag:"--priority"},{flag:"--type"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{flag:"--remove-tags",aliases:["--remove_tags"]},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--add-ac",aliases:["--add_ac"]},{flag:"--remove-ac",aliases:["--remove_ac"]}],Ba=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{flag:"--id"},{short:"-d",flag:"--description"},{flag:"--type"},{flag:"--template"},{flag:"--create-mode"},{flag:"--create_mode"},{flag:"--schedule-preset"},{flag:"--schedule_preset"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},{flag:"--completed_at"},{short:"-p",flag:"--priority"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{short:"-b",flag:"--body"},{flag:"--body-file"},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--author"},{flag:"--message"},...qp,...Bp,{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--fixed_version"},{flag:"--dep"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--reminder"},{flag:"--event"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--allow-duplicate",value_type:"boolean"}],Hp=[{flag:"--transaction-id",value_name:"value"},{flag:"--stdin-json"},{flag:"--dry-run"},{flag:"--create-compensation",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--author",value_name:"value"}],Vp=[{flag:"--id",value_name:"item-id"},{flag:"--transaction-id",value_name:"value",required:!0},{flag:"--reason",value_name:"value"},{flag:"--file",value_name:"value",repeatable:!0},{flag:"--doc",value_name:"value",repeatable:!0},{flag:"--test",value_name:"value",repeatable:!0},{flag:"--comment",value_name:"value",repeatable:!0},{flag:"--note",value_name:"value",repeatable:!0},{flag:"--learning",value_name:"value",repeatable:!0},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",value_name:"value"},{flag:"--actual-result",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--dry-run"},{flag:"--force"},{flag:"--author",value_name:"value"}],Wp=[{flag:"--id",value_name:"item-id"},{flag:"--status",value_name:"open|in_progress"},{flag:"--message",value_name:"value"},{flag:"--force"},{flag:"--author",value_name:"value"}],Kp=[{flag:"--id",value_name:"item-id"},{flag:"--title",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--allow-duplicate",value_type:"boolean"}],Yp=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Xp=[{flag:"--id",value_name:"item-id"},{flag:"--stdin-json"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},{flag:"--body-file"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},...Gp,...qp,{flag:"--fixed_version"},...Bp,{flag:"--author"},{flag:"--message"},{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--force"}],Jp=[{flag:"--filter-status",list:!0},{flag:"--filter-type",list:!0},{flag:"--filter-tag",list:!0},{flag:"--filter-priority",list:!0},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee",list:!0},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint",list:!0},{flag:"--filter-release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...ep,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...Gp,{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--repro_steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--expected_result"},{flag:"--expected"},{flag:"--actual-result"},{flag:"--actual_result"},{flag:"--actual"},{flag:"--affected-version"},{flag:"--affected_version"},{flag:"--fixed-version"},{flag:"--fixed_version"},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--allow-unresolved-deps"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Ga=[{flag:"--view"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--full-period"},{flag:"--full_period"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--status"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--include"},{flag:"--recurrence-lookahead-days"},{flag:"--recurrence-lookback-days"},{flag:"--occurrence-limit"},{flag:"--limit"},{flag:"--format"}],Zp=[{flag:"--id"},{flag:"--op"},{flag:"--author"},{flag:"--from"},{flag:"--to"},{flag:"--limit"},{flag:"--unbounded"},{flag:"--compact"},{flag:"--raw"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--stream"}],Qp=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{flag:"--cursor-mode",value_name:"batch|row"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--follow"},{flag:"--interval-ms",value_type:"number"}],Ha=Va([{flag:"--for",value_name:"intent"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit",aliases:["--max-items"]},{flag:"--after"},{flag:"--format"},{flag:"--depth"},{flag:"--fields",list:!0},{flag:"--section"},{flag:"--activity-limit"},{flag:"--stale-threshold"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--no-extension-health"},{flag:"--no-tags"}],new Set(["--limit","--after","--format","--fields","--section","--activity-limit","--stale-threshold","--explain-ranking","--explain_ranking","--no-extension-health","--no-tags"])),em=[{flag:"--id",value_name:"item-id"},{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--depth"},{flag:"--full",value_type:"boolean"},{flag:"--fields",list:!0},{flag:"--at"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--format"}],tm=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],nm=[{flag:"--id",value_name:"item-id"},{flag:"--format"},{flag:"--max-depth"},{flag:"--collapse"},{flag:"--summary"},{flag:"--full"},{flag:"--node-limit"},{flag:"--edge-limit"},{flag:"--token-budget"},{flag:"--cursor"},{flag:"--direction"},{flag:"--kind",list:!0}],rm=[{flag:"--kind",list:!0},{flag:"--max-depth"},{flag:"--limit"},{flag:"--after"},{flag:"--direction"},{flag:"--max-paths"},{flag:"--sample"},{flag:"--exempt-isolate",list:!0},{flag:"--exempt-isolate-type",list:!0},{flag:"--save-baseline"},{flag:"--rebuild"},{flag:"--clear"},{flag:"--summary"},{flag:"--full"}],om=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],ot=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],im=[],sm=[{flag:"--for",value_name:"intent"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit"},{flag:"--blocked-limit"},{flag:"--blocked_limit"},{flag:"--ready-only"},{flag:"--ready_only"},{flag:"--format"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]}],am=Va([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--mode"},{flag:"--semantic"},{flag:"--hybrid"},{flag:"--match-mode"},{flag:"--min-score"},{flag:"--count"},{flag:"--semantic-weight"},{flag:"--include-linked"},{flag:"--title-exact"},{flag:"--phrase-exact"},{flag:"--highlight"},{flag:"--compact"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--format"},{flag:"--limit"},{flag:"--after"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--assignee",list:!0},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--parent"},...Qf],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),cm=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],lm=[{flag:"--eager-tags"}];var cx=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],lx=Qo.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),dx=Qo.filter(e=>e.flag!=="--status");function Zo(e){let t=new Map;for(let n of e)for(let r of[n.flag,...n.aliases??[]]){let o=t.get(r)??[];o.push(n),t.set(r,o)}return t}var ux=Zo(Wa),fx=Zo(Xa),px=new Map([["assurance",fx],["plan",ux],["workspace",Zo(im)],["workspace snapshot",Zo(ot)]]);function dm(e=vn){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=px.get(n);if(!o)throw new Error(`Positional action ${t} has no flag-contract index for ${n}.`);let i=r.map(s=>{let a=o.get(s)??[];if(a.length!==1)throw new Error(`Positional action ${t} accepted flag ${s} does not resolve to exactly one ${n} flag contract.`);return a[0]});return[t,i]})}var mx=dm(),d5=new Map([["list",Qo],["list-all",dx],...cx.map(e=>[e,lx]),["templates",Ba],["cal",Ga],["ctx",Ha],["test-runs-worker",Mp],["init",_p],["config",gp],["extension",Ka],["package",qa],["packages",qa],["install",yp],["upgrade",bp],["create",Ba],["item mutate",Hp],["item complete",Vp],["item reopen",Wp],["copy",Kp],["focus",Yp],["aggregate",tp],["calendar",Ga],["context",Ha],["get",em],["guide",tm],["search",am],["next",sm],["eval",om],["workspace",ot],["workspace position",im],["workspace snapshot",ot],["workspace snapshot create",ot],["workspace snapshot list",ot],["workspace snapshot inspect",ot],["workspace snapshot restore",ot],["workspace snapshot delete",ot],["history",ap],["history-redact",lp],["history-repair",dp],["history-author-acknowledge",up],["history-compact",fp],["merge",cp],["schema",pp],["profile",mp],["plan",Wa],["activity",Zp],["events",Qp],["restore",Tp],["update",Xp],["update-many",Jp],["close",wp],["close-many",vp],["delete",Sp],["append",Ep],["comments",np],["notes",rp],["learnings",op],["files",ip],["docs",sp],["deps",nm],["graph",rm],["test",Dp],["test-all",Pp],["telemetry",Lp],["health",Up],["assurance",Xa],...mx,["validate",zp],["gc",Fp],["stats",$p],["duplicates",jp],["contracts",cm],["completion",lm],["claim",kp],["release",Ap],["start-task",xp],["pause-task",Cp],["close-task",Ip],["meet",Ya],["event",Rp],["remind",Np]]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19a97f60-3b6e-5653-a652-02aebaf5afdd")}catch{}})();var um={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},fm={if:{required:["field"]}};Reflect.set(fm,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var pm={oneOf:[{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[fm],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:um,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:um,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6968f481-8384-5e3b-8ac0-b0972d08eeb1")}catch{}})();var gr={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:uo,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},ifAbsent:{type:"boolean"},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},mm={assurance:{definition:pm,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},_x=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Ja={subcommand:{type:"string",enum:[..._x]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...kc]},mode:{type:"string",enum:[...Ec]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Rr]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...Tc]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},Za={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},hr={action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read linked commands).",examples:["schema","tracker","auto"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Return non-zero exit when health/validate/extension-doctor warnings are present."},failOnWarn:{description:"Alias for strictExit in health/validate/extension-doctor action payloads."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, or context outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Continuation cursor resuming a bounded listing or traversal after this previously returned id.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},_m={assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, or risk.",examples:["list","run","derive","promote","risk"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{name:{description:"Custom item type name (add-type/remove-type/show), custom status id (show-status/add-status/remove-status), or custom field key (add-field/remove-field/show-field). Required for those subcommands.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b81a68c1-565d-56f6-a0eb-35d2c737bdb7")}catch{}})();var hx=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],yx=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],bx=new Set(["action","cwd","options",...Object.keys(gr).filter(e=>e!=="severity")]);var wx={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},vm=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],T5=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(gt.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Te(e){return za(e)}var vx=Te([...Da.map(e=>e.param),...Jo.map(e=>e.param),"assignee","closeReason","completedAt"]),Em=Te([...Pa.map(e=>e.param),...Jo.map(e=>e.param),"force"]),Ex=Te([...Ma.map(e=>e.param),...Em.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),kx=Te([...Fa.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),gm=Te([...ja.map(e=>e.param),"past","section"]),Tx=Te([...$a.map(e=>e.param),"stream"]),Qa=Te([...Oa.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),En=Qa.filter(e=>e!=="all"&&e!=="status"),Sx=Qa.filter(e=>e!=="status"),At=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],Ax=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],xx=Te([...Ra.map(e=>e.param),"count","completion","includeUnparented"]),Cx=Te(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Na.map(e=>e.param)]),hm=Te(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),ge=["author","message","force"],km=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],yr=["author","assignee","message","force"],Ix=["target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function ym(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:Ix}}}var bm={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},wm={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},ei={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...ym("extension"),...ym("package"),"package-upgrade":wm,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:wm,create:{required:["title","description","type","status","priority","message"],optional:vx},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Qa,mutuallyExclusiveWhen:At},"list-all":{optional:Sx,mutuallyExclusiveWhen:At},"list-draft":{optional:En,mutuallyExclusiveWhen:At},"list-open":{optional:En,mutuallyExclusiveWhen:At},"list-in-progress":{optional:En,mutuallyExclusiveWhen:At},"list-blocked":{optional:En,mutuallyExclusiveWhen:At},"list-closed":{optional:En,mutuallyExclusiveWhen:At},"list-canceled":{optional:En,mutuallyExclusiveWhen:At},aggregate:{optional:xx},guide:{optional:["list","format","depth"]},context:{optional:gm},ctx:{optional:gm},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:Cx,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:bm,event:bm,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...hm,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...ge],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...ge],oneOfRequired:[["id"],["all"]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...ge]},schema:{required:["subcommand"],optional:["name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...vm,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...ge]},activity:{optional:Tx},restore:{required:["id","target"],optional:ge},update:{required:["id"],optional:Em,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:Ex,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...km,...ge]},"close-many":{optional:kx},delete:{required:["id"],optional:["dryRun",...ge]},append:{required:["id","body"],optional:ge},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...ge],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...ge],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...ge],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...ge],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...ge],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["add","addJson","remove","removeIndex","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...ge],mutuallyExclusive:[["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:Ax},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...hm,...yr],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:yr},"start-task":{required:["id"],optional:yr},"pause-task":{required:["id"],optional:yr},"close-task":{required:["id"],optional:["text","validateClose",...yr]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},Ox=Object.freeze(Object.fromEntries(gt.map(e=>[e,ei[e]])));function Tm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function Rx(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=hr[e];return{...n,description:r?.description??Tm(e),...r?.examples?{examples:r.examples}:{}}}function Nx(e,t){if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(Za,t))return Za[t];let n=_m[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:hr[t]}function Dx(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=Nx(e,t);return{...r,description:o?.description??Tm(t),...o?.examples?{examples:o.examples}:{}}}function Px(e,t){let n=mm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(Ja,t)?Ja[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:gr[t]}function Lx(e,t){let n={action:{const:e,description:hr.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=Px(e,r);o&&(n[r]=Dx(e,r,o))}return n}function Mx(e,t){let n=t.flat();return t.map(r=>{let o=n.filter(i=>!r.includes(i));return{required:[...r],...o.length>0?{not:{anyOf:o.map(i=>({required:[i]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function Fx(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:{properties:{[n.property]:{const:n.value}},required:[n.property]},then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:{required:[n.property]},then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:Te(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function Sm(e){if(!Object.prototype.hasOwnProperty.call(ei,e))return;let t=ei[e],n=wx[e]??[];return Te(["action",...hx,...Un(e)!==void 0?yx:[],...n,...t.required??[],...t.optional??[]])}function $x(e){let t=ei[e],n=Te(t.required??[]),r=Sm(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:Lx(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=Mx(e,t.oneOfRequired));let i=Fx(t);return i.length>0&&(o.allOf=i),o}function Am(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,o)=>n()[o],has:(r,o)=>o in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,o)=>{let i=Reflect.getOwnPropertyDescriptor(n(),o);return i&&(i.configurable=!0),i}})}var ec="4.10.1",xm=ec.split(".")[0],Cm="1.4.0",jx=Am(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${xm}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":ec,type:"object",oneOf:gt.map(e=>$x(e))}));function Ux(e,t){let n=Rx(e,t);if(typeof n.type=="string")return n;let o=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(o){let{anyOf:a,...c}=n;return{...o,...c}}let{anyOf:i,...s}=n;return{...s,type:"string"}}function zx(){let e={action:{type:"string",description:hr.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(gr).sort())e[t]=Ux(t,gr[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Cm,type:"object",additionalProperties:!1,required:["action"],properties:e}}var qx=Am(zx);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4e5eed5-94c2-536a-8685-e20b735de480")}catch{}})();var O5=new Set([...Xl,...Jl]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="167b98d4-a5b5-581d-ac0a-17e8e3bfc490")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fde4fea5-94d6-53e2-bfbc-bff71d828c01")}catch{}})();var Zx=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),LW=new Set([...Zx].filter(e=>e!=="file"));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var Qx="2026-07-15T06:22:12.276Z",eC=Date.parse(Qx),tC=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Im=e=>typeof e=="string"?e:"",nC=e=>{let t=e??{},n=Im(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(Im(t.ts))>=eC);return tC[r][o]};function rC(e,t,n=20,r=new Set,o=!1){let i=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let _;try{_=JSON.parse(p)}catch{continue}l+=1;let y=nC(_);if(y!=="attributed"){if(d+=1,y==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[y]+=1,o&&y==="actionable_unknown"&&s.push({item_id:e,line:f+1}),i.length<c&&i.push({item_id:e,line:f+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:s}}function oC(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let s of i.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var Om=async(e,t=20,n=!1)=>{let r=nc.join(e,"history"),o;try{o=(await tc.readdir(r)).filter(E=>E.endsWith(".jsonl")).sort((E,v)=>E.localeCompare(v))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,_="_workspace.jsonl",y=new Set;if(o.includes(_))try{y=oC(await tc.readFile(nc.join(r,_),"utf8"))}catch{y=new Set}for(let E of o){let v;try{v=await tc.readFile(nc.join(r,E),"utf8")}catch{continue}let C=E.slice(0,-6),k=rC(C,v,t-s.length,y,n);c+=1,l+=k.checked_events,d+=k.unknown_event_count,u+=k.legacy_unknown_event_count,f+=k.actionable_unknown_event_count,p+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&i.add(C),s.push(...k.samples),n&&a.push(...k.actionable_events)}let b=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...i].sort((E,v)=>E.localeCompare(v)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import iC from"node:fs/promises";import De from"node:path";import sC from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var aC=["path","scope","note"],cC=["pattern","glob","path","scope","note"],lC=["path"],dC=["from","to"],uC=new Set(["note","scope"]);function Nm(e){let t=e??"project";if(!wi.includes(t))throw new h(`Invalid scope "${e}". Valid scopes: ${wi.join(", ")} (default: project).`,g.USAGE);return t}function rc(e){if(e.startsWith("```")||e.includes(`
|
|
112
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||Ta(e)}function fC(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function pC(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!rc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let i=e.slice(t+2,-1).trim();if(i.length>0&&fC(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function mC(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=pC(r);if(i!==void 0)return[i]}Nf(r,"--add",`${t} path`,rc(r));let o=rc(r)?bn(n,"--add"):{path:r};if(wn(o,"--add",aC),!o.path)throw new h(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:o.path,scope:Nm(o.scope),note:o.note?.trim()||void 0}]}):[]}function _C(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=bn(n,"--add-glob");wn(r,"--add-glob",cC);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new h("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:o,scope:Nm(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function gC(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=bn(n,"--remove"),o=Object.keys(r).filter(i=>uC.has(i.toLowerCase()));if(o.length>0)throw new h(`--remove identifies a linked artifact by path only and does not accept ${o.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(wn(r,"--remove",lC),!r.path)throw new h("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function hC(e){return e?e.map(t=>{let n=bn(t,"--migrate");wn(n,"--migrate",dC);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new h("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:o}}):[]}function br(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function yC(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>br(i.path,n))),o=[...new Set(t.map(i=>br(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new h(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function ti(e){return e.split(De.sep).join("/")}function oc(e,t,n=process.cwd()){let r=e.trim();if(dr(r))return r;if(De.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return ti(r.replaceAll("\\",De.sep));let o=De.relative(t,n);return o.startsWith(`..${De.sep}`)||o===".."||De.isAbsolute(o)?ti(De.normalize(r)):ti(De.relative(t,De.resolve(n,r)))}async function bC(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=De.isAbsolute(o.pattern),s=await sC(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>oc(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)r.push({path:c,scope:o.scope,note:o.note})}return r}function wC(e,t,n){if(t===void 0)return e;if(!n)throw new h("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function vC(e){return`${e.path}::${e.scope}`}function Dm(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Pm(e){return[...new Map(e.map(t=>[vC(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function EC(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],i=[],s=[];for(let a of n){if(dr(a)){s.push(a.trim());continue}let c=De.isAbsolute(a)?a:De.resolve(t,a);try{(await iC.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&xn(l)){o.push(a);continue}i.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:i,remote_references:s}}function kC(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=br(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=br(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>br(s,r)),count:o}}function TC(e,t,n,r){for(let i of t)e.some(s=>s.path===i.path&&s.scope===i.scope)||e.push(i);if(n.length>0)for(let i=e.length-1;i>=0;i-=1)n.includes(e[i].path)&&e.splice(i,1);let o=Pm(e);return r?o:Dm(o)}async function Rm(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await EC(t,e.workspaceRoot):void 0}}async function ni(e,t,n,r){let{metadataKey:o}=r,i=fr(),s=re(process.cwd(),n.path),a=Wr(s),c=process.cwd();await Oe(s);let l=await te(s),d=ue(l,Y()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),p=await i.resolveList(t.remove,"--remove"),_=await i.resolveList(t.migrate,"--migrate"),y=mC(u,r.bareNoun).map(ae=>({...ae,path:oc(ae.path,a,c)})),b=_C(f),E=await bC(b,a,c),v=wC([...y,...E],t.note,y.length>0||b.length>0),C=gC(p).map(ae=>oc(ae,a,c)),k=hC(_);if(yC(v,C,k),!(v.length>0||C.length>0||k.length>0)){let ae=await Ue(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!ae)throw new h(`Item ${e} not found`,g.NOT_FOUND);let K=(await Ne(ae,{schema:l.schema})).document.metadata[o]??[];return Rm({id:ae.id,artifacts:K,changed:!1,options:t,workspaceRoot:a})}let P=Fe(t.author,l.author_default),M=await Vo({pmRoot:s,settings:l,id:e,op:r.op,author:P,message:t.message,force:t.force,skipNoop:!0,mutate(ae){let O=ae.metadata,K=O[o]??[],ze=[...K],ct=kC(ze,v,C,k),kn=TC(ze,ct.adds,ct.removes,r.supportsAppendStable&&t.appendStable===!0);kn.length>0?O[o]=kn:delete O[o];let _c=!xe(K,kn);return{changedFields:_c?[o]:[],warnings:_c&&ct.count>0?[`path_migrations_applied:${ct.count}`]:[]}}}),L=M.item[o]??[],W=M.warnings.find(ae=>ae.startsWith("path_migrations_applied:")),J=W?Number(W.slice(24)):0;return Rm({id:M.item.id,artifacts:L,changed:M.changedFields.includes(o),migrationsApplied:J,options:t,workspaceRoot:a})}function ri(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Lm(e,t,n){let r=await ni(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ri(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();async function Mm(e,t,n){let r=await ni(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ri(r,"files")}import{readFileSync as SC}from"node:fs";import oi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var AC=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),jm=new Set(["--pm-path","--path","--author"]),xC={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},CC=new Set(["-p","--package"]),IC=new Set(["-c","--call"]),OC=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),RC=new Set(["-C","--prefix","--userconfig","--cache"]);var NC=new Set(["exec","x"]);function DC(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function PC(e,t=process.cwd()){let n=LC(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(Fm(r)||$m(r,t))return o;if(r==="node"&&o[0]&&$m(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?ic(o):r==="pnpm"?$C(o):r==="npm"?jC(o):null;return i&&(Fm(i.command)||FC(i.command))?i.args:null}var Um=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of DC(i)){let c=PC(a),l=c?UC(c):null,d=l&&AC.has(l.subcommand)?zC(l.remaining,xC[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${o}-`)===!0&&u.length>o.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function LC(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Fm(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function MC(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function FC(e){let t=MC(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function $m(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=oi.resolve(t,e);try{return JSON.parse(SC(oi.join(oi.dirname(oi.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function ic(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let i=o[1];return i?{command:i,args:e.slice(t+1)}:null}if(IC.has(r)){t+=1;break}t+=CC.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function zm(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function $C(e){let t=zm(e,OC);return t?.subcommand!=="dlx"?null:ic(t.args)}function jC(e){let t=zm(e,RC);return!t||!NC.has(t.subcommand)?null:ic(t.args)}function UC(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(jm.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function zC(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(jm.has(r)||t.has(r))&&(n+=1)}}import{execFile as qC}from"node:child_process";import{readFile as BC}from"node:fs/promises";import GC from"node:path";import{promisify as HC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var VC=HC(qC),sc=1,WC="linked-test-trust.json";function KC(e){return GC.join(Yr(e),WC)}function qm(){return{version:sc,acknowledged:{}}}async function YC(e){try{let t=JSON.parse(await BC(KC(e),"utf8"));return t.version!==sc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?qm():{version:sc,acknowledged:t.acknowledged}}catch{return qm()}}async function Bm(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await VC("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Gm(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function XC(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Pe(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function wr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function JC(e){return se(R({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}function ZC(e,t,n){let r=JC(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let i=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!XC(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...wr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...wr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...wr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...wr(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...wr(o,t)}}async function Hm(e,t,n){let r=await YC(e);return t.map(o=>ZC(o,n,r))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Vm(e){return e.includeBody?Ho(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):sr(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var QC=5;async function Wm(e,t,n){let r=await Wo(e,t),i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),s=n?Number.POSITIVE_INFINITY:QC,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function ac(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),o=[n],i=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&o.length>1)return o.push(n),!0;if(!i.has(c)){if(i.add(c),o.push(c),s(c))return!0;o.pop(),i.delete(c)}}return!1};return s(n)?[...o]:[...e,n]}function eI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function tI(e,t,n,r){for(let o of e.dependencies??[]){if(typeof o!="object"||o===null||typeof o.id!="string")continue;let i=r.resolve(o.kind);if(!i?.hierarchy)continue;let s=n.get(o.id.toLowerCase());s&&(i.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Km(e,t=Yt()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),r=new Map(e.map(o=>[o.id,[]]));for(let o of[...e].sort((i,s)=>i.id.localeCompare(s.id))){let i=r.get(o.id),s=eI(o.parent,n);s&&i.push(s),tI(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function Ym(e,t,n=Yt()){let r=wa(e,s=>t?Si(s,t):s==="closed"||s==="canceled",n),o=Km(e,n),i=r.cycles.map(s=>s.item_ids);return{cycle_count:i.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(i.flat())].sort(),cycle_sample_paths:i.map(s=>ac(s,o).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function Xm(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),o=new Set(r),i=t.filter(s=>{let a=tn(s.status,e);return a!==void 0&&o.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:i.length,affected_item_ids:i.slice(0,n),affected_item_ids_truncated:i.length>n}}function Jm(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function xt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function cc(e){return xt(e).replace(/\/+$/,"")}function Xe(e){let t=de(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d466293-869d-54bb-b07d-facb3be51e8c")}catch{}})();var iI=["src","tests","docs"],sI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],aI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),cI=["resolution","expected_result","actual_result"],lI=["default","tracked-all","tracked-all-strict"],Zm=["core","strict","custom"],ai=["off","warn","error"],uc=["author","acceptance_criteria","estimated_minutes","close_reason"],n_=[...uc,"reviewer","risk","confidence","sprint","release"],mc=Array.from(new Set(n_)),dI={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},uI={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},fI={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},pI={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},mI={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},_I=32*1024*1024,gI=1e4,r_=40,at=5,hI=4096,yI=255,bI=oI(rI);function o_(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?o_(r):r);return t}function wI(e){return{...e,checks:e.checks.map(t=>({...t,details:o_(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function li(e,t){return Dt(e,t)??e}function vr(e,t){return t.terminal_statuses.has(li(e,t))}function Ct(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ii(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function vI(e){let t=Ct(hi),n={blocked_reason:Ct(Ot.blocked_reason),resolution:Ct(Ot.resolution),actual_result:Ct(Ot.actual_result)},r=Ct(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:Ct(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Ct(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Ct(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ii(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:ii(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ii(o.resolution,n.resolution)?"default":"settings",actual_result:ii(o.actual_result,n.actual_result)?"default":"settings"}}}function EI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Zm.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${Zm.join(", ")}.`,g.USAGE)}function kI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ai.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ai.join(", ")}.`,g.USAGE)}function TI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ai.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ai.join(", ")}.`,g.USAGE)}function SI(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>dI[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function AI(e,t,n){let r=SI(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...uc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...n_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...uc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var xI=new Set(["acceptance_criteria","estimated_minutes"]);function CI(e,t,n,r){return!r&&xI.has(t)&&vr(e.status,n)?!1:t==="author"?!de(e.author):t==="acceptance_criteria"?!de(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?li(e.status,n)===n.close_status&&!de(e.close_reason):t==="reviewer"?!de(e.reviewer):t==="risk"?!de(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!de(e.confidence):t==="sprint"?!de(e.sprint):!de(e.release)}function II(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new h(`Unknown --scan-mode value "${e}". Supported values: ${lI.join(", ")}.`,g.USAGE)}function OI(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return he.resolve(t);let n=he.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return he.dirname(he.dirname(n));let o=he.resolve(process.cwd()),i=Qm(n),s=Qm(o),a=he.relative(i,s);return a.length===0||!a.startsWith("..")&&!he.isAbsolute(a)?n:o}function Qm(e){try{return nI.native(e)}catch{return he.resolve(e)}}function RI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function i_(e,t,n){let r=t.length>0?he.join(e,t):e,o;try{o=await pc.readdir(r,{withFileTypes:!0})}catch(i){if(H(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?he.join(t,i.name):i.name;if(i.isDirectory()){if(aI.has(i.name))continue;await i_(e,s,n);continue}i.isFile()&&n.push(xt(s))}}async function e_(e){let t=[];for(let n of iI)await i_(e,n,t);for(let n of sI){let r=he.join(e,n);try{(await pc.stat(r)).isFile()&&t.push(xt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function NI(e){try{let{stdout:t}=await bI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:_I,windowsHide:!0,timeout:gI}),n=t.split("\0").map(r=>xt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function DI(e,t){let n=new Set,r=cc(Xt);r.length>0&&n.add(r);let o=cc(he.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function t_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function PI(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await NI(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await e_(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await e_(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function X(e,t=at){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function It(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=X(e,r_);return{values:n.values,truncated:n.truncated,total:e.length}}var LI={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},MI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function FI(e){let t=e.missing_fields.map(n=>`${LI[n]} "${MI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function $I(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,o=r?n.filter(s=>typeof s=="string"):nf(t);if(o.length===0)return;let i=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:o,...i?{fix_hints_truncated:!0}:{}}}function jI(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var UI="validate_metadata_duplicate_issue_codes";function zI(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:at,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${UI}:${e.length}`]}}function qI(){return Object.fromEntries(mc.map(e=>[e,[]]))}function BI(e,t,n){let r=qI();for(let o of e)for(let i of mc)CI(o,i,t,n)&&r[i].push(o.id);return r}function GI(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${uI[o]}:${i.length}`)}return r.push(...n),r}function HI(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=fI[r];n[s]=i}return n}function VI(e,t,n){let r=[];for(let o of e.required_fields){let i=t[o];if(i)for(let s of i){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:o})}}return r}function WI(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=pI[o],a=mI[o];if(!s||!a)continue;let c=X(i,r?i.length:at);e[s]=c.values,e[a]=c.truncated}}function KI(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:de(n.get(o)?.resolution)})):[]}function YI(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:de(n.get(o)?.type)})):[]}function XI(e,t,n,r,o){let i=new Map(e.map(E=>[E.id,E])),s=t.profile==="strict",a=BI(e,n,s),c=pf(e,{configuredPrefixes:o}),l=zI(c,r),d=GI(t,a,l.warnings),u=HI(t,a),f=VI(t,a,i),p=mf(f),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...mc],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),WI(_,t,a,r);let y=KI(t,a,i),b=YI(t,a,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:_},warnings:d,closeReasonBackfillRows:y,estimateBackfillRows:b}}function JI(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(li(f.status,t))),i=[],s=[];for(let f of o){let p=cI.filter(_=>!de(f[_]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:de(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:at,l=X(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>FI(f)),u=X(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:o.length,missing_resolution_items:i.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function ZI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function QI(e,t="pm",n=dn()){let r=new Set(e.map(i=>i.id)),o=[...e].sort((i,s)=>i.id.localeCompare(s.id));return new Map(o.map(i=>{let s=new Set,a=Xe(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=Xe(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>Xe(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=Xe(i.definition_of_ready);return tO(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function eO(e,t,n){let r=kf(e,n?d=>vr(d,n):void 0),o=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),i=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:at,a=X(o,s),c=X(i,s),l=X(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:e.length,dangling_reference_count:o.length+i.length,active_dangling_reference_count:o.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:o.length>0?[`validate_dangling_dependency_references:${o.length}`]:[]}}function tO(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${ZI(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(o=>o[1].toLowerCase()))].sort((o,i)=>o.localeCompare(i))}function nO(e){let t=0,n=new Map,r=new Map,o=[],i=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,o.push(d),i.add(d);for(let f of e.get(d)??[])n.has(f)?i.has(f)&&r.set(d,Math.min(r.get(d),n.get(f))):(a(f),r.set(d,Math.min(r.get(d),r.get(f))));if(r.get(d)!==n.get(d))return;let u=[];for(;o.length>0;){let f=o.pop();if(i.delete(f),u.push(f),f===d)break}u.sort((f,p)=>f.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function rO(e,t="pm"){let n=QI(e,t),r=nO(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>ac(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function oO(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function ci(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function iO(e,t){let n=ci(e).split("/").filter(Boolean),r=ci(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function sO(e,t){let n=ci(t),r=ci(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=iO(e,t);return!i&&!s&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function aO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function cO(e,t,n){let r=t==="docs_unowned"?"docs":"files",o;return n.flatMap(i=>(r==="docs"?i.docs??[]:i.files??[]).map(s=>({item:i,link:s}))).forEach(({item:i,link:s})=>{if(s.scope!=="project")return;let a=xt(s.path);if(a.length===0||a===e)return;let c=sO(e,a);c!==null&&aO(o,i,c.score)&&(o={item:i,score:c.score,confidence:c.confidence})}),o?{id:o.item.id,type:o.item.type,title:o.item.title,status:o.item.status,confidence:o.confidence}:null}function lO(e,t){return e.map(n=>{let r=oO(n),o=r==="docs_unowned"?"docs":"files",i=cO(n,r,t),s=i?.id??"<id>";return{path:n,classification:r,owner_candidate:i,remediation_hint:`pm ${o} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function dO(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function uO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=Xe(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function fO(e,t,n,r,o){let i=Xe(t.parent),s=i?n.get(r.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!vr(s.status,o)}}function pO(e,t,n,r){let o=Xe(e.blocked_by),i=Xe(e.blocked_reason),s=i?.toLowerCase(),a=li(e.status,n),c=[];return t.has(a)?(!o&&!i&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(o&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function mO(e,t,n,r){let o=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!vr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=uO(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=Xe(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&vr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(fO(c,u,o,i,n))),t){let f=pO(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((p,_)=>p.localeCompare(_))})}}return a}function _O(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function si(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function lc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function gO(e,t,n,r,o){let i=[];e.closureLikeRows.length>0&&i.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&i.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&i.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=si("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=si("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=si("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=si("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=lc("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=lc("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=lc("validate_legacy_hierarchy_parent_divergence",r,o.legacyHierarchyDivergence);return[...i,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...f?[f]:[]]}function hO(e){let t=xt(e);return t.length>hI||t.split(/[\\/]/).some(n=>n.length>yI)}async function yO(e,t){let n=he.isAbsolute(t)?t:he.resolve(e,t);if(hO(n))return!1;try{let r=await pc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return RI(r,["ENOENT","ENOTDIR"])}}async function bO(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(o=>[...(o.files??[]).map(i=>({item:o,artifact:i,link_kind:"files"})),...(o.docs??[]).map(i=>({item:o,artifact:i,link_kind:"docs"}))]);for(let{item:o,artifact:i,link_kind:s}of r){if(i.scope!=="project")continue;if(dr(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=xt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await yO(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function wO(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:DI(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>t_(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!t_(p,l)),f={};if(d.length>0){let p=It(d,i);f.pm_internals={count:d.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function vO(e,t,n,r,o,i,s,a="pm"){let c=mO(e,t,o,i);_O(c);let l=rO(c.activeItems,a),d=Ym(e,o),u=Xm(o,e,s?Number.POSITIVE_INFINITY:at),f=[...gO(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...Jm(u)],p=s?Number.POSITIVE_INFINITY:at,_=X(c.closureLikeRows.map(L=>`${L.id}:${L.fields.join(",")}`),p),y=X(c.terminalParentRows.map(L=>`${L.id}:${L.parent_id}:${L.parent_status}`),p),b=X(c.staleBlockerRows.map(L=>`${L.id}:${L.status}:${L.reasons.join(",")}`),p),E=X(l.cycle_item_ids,p),v=X(l.cycle_sample_paths,p),C=X(d.cycle_item_ids,p),k=X(d.cycle_sample_paths,p),S=X(d.cardinality_violation_rows,p),P=X(d.parent_divergence_rows,p),M=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:M?"error":f.length===0?"ok":"warn",ok:!M&&f.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:y.values,active_terminal_parent_rows_truncated:y.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:b.values,stale_blocker_rows_truncated:b.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:E.values,dependency_cycle_item_ids_truncated:E.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:C.values,parent_cycle_item_ids_truncated:C.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:S.values,hierarchy_cardinality_violation_rows_truncated:S.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:P.values,hierarchy_parent_divergence_rows_truncated:P.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:f,terminalParentFixRows:c.terminalParentFixRows}}async function EO(e,t,n,r,o,i){let s=await bO(e,t),a=new Map(e.map(O=>[O.id,O])),c=[...new Set(s.missingLinkedPaths)].sort((O,K)=>O.localeCompare(K)),l=await PI(t,r),d=wO(l,n,t,r,o,i),u=d.candidateFiles.filter(O=>!s.linkedProjectPaths.has(O)),f=lO(u,e),p=hf(c,d.candidateFiles),_=new Map(p.map(O=>[O.path,O.classification])),y=p.filter(O=>O.classification==="moved").length,b=s.staleLinkRows.map(O=>({...O,classification:_.get(O.path)??"deleted"})).sort((O,K)=>O.item_id.localeCompare(K.item_id)||O.path.localeCompare(K.path)||O.link_kind.localeCompare(K.link_kind)),E=[];d.strictModeForcesPmInternals&&E.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&E.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&E.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((O,K)=>O.localeCompare(K)),C=It(v,i),k=It(c,i),S=It(u,i),P=It(f.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),i),M=i?f:It(dO(f),!1).values,L=It(yf(p),i),W=b.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),J=wf(W,O=>{let K=a.get(O);return K?{type:K.type,title:K.title,status:K.status}:void 0}),ae=i?J:It(vf(J),!1).values;return{check:{name:"files",status:E.length===0?"ok":"warn",ok:E.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:r_,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:o,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:k.total,missing_linked_paths:k.values,missing_linked_paths_truncated:k.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:c.length-y,missing_linked_path_classifications:L.values,missing_linked_path_classifications_truncated:L.truncated,missing_linked_path_rows_count:J.length,missing_linked_path_rows:ae,orphaned_paths_count:u.length,orphaned_paths_total:S.total,orphaned_paths:S.values,orphaned_paths_truncated:S.truncated,orphaned_path_classifications:P.values,orphaned_path_classifications_truncated:P.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:M}},warnings:E,staleLinkPruneRows:b}}function s_(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function kO(e,t,n){return`${e}:${t}:${s_(n)}`}function TO(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=s_(o.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function SO(e,t,n,r){let o=new Set(e.map(S=>S.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(S=>(S.tests??[]).map(P=>({item:S,linkedTest:P}))),d=await Bm(Gm()),u=await Hm(r,l.map(({linkedTest:S})=>S),d),f=TO(l,u);for(let{item:S,linkedTest:P}of l){if(typeof P.command!="string"||P.command.trim().length===0)continue;i+=1;let M=Um(P.command,t);if(M.length!==0){s+=M.length;for(let L of M)a.add(L),o.has(L.toLowerCase())||c.push(kO(S.id,L,P.command))}}let p=[...new Set(c)].sort((S,P)=>S.localeCompare(P)),_=[...new Set(p.map(S=>S.split(":")[1]??""))].filter(S=>S.length>0).sort((S,P)=>S.localeCompare(P)),y=[];p.length>0&&y.push(`validate_command_references_stale_pm_ids:${p.length}`),f.length>0&&y.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let b=n?Number.POSITIVE_INFINITY:at,E=X(p,b),v=X(_,b),C=X([...a].sort((S,P)=>S.localeCompare(P)),b),k=X(f,b);return{check:{name:"command_references",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:C.values,unique_referenced_pm_ids_truncated:C.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:_.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:E.values,stale_pm_id_reference_rows_truncated:E.truncated}},warnings:y}}function AO(e,t){let n=Bc(e.map(c=>({ref:c.id,version:zc(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let o=t?Number.POSITIVE_INFINITY:at,i=X(n.outdated,o),s=X(n.ahead,o),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:Ur,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var fc="pm validate auto-fix";async function xO(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:fc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new h("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function dc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function CO(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>dc(a)===null))try{await xO(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>dc(a)!==null)){let a=dc(s),c=i.get(a);c?c.push(s):i.set(a,[s])}for(let s of i.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Mm(a.item_id,{remove:c,message:fc},t):await Lm(a.item_id,{remove:c,message:fc},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}function IO(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function OO(e,t,n,r){let o=await Sf(e,new Set(t.map(b=>b.id)),n,{schema:r.schema,extensionFieldNames:nt(Y())}),i=[];o.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${o.unreadable_item_files.length}`),o.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${o.duplicate_item_ids.length}`),o.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${o.history_conflict_marker_streams.length}`),o.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${o.history_unparseable_streams.length}`),o.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${o.resurrected_items.length}`),o.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${o.unparseable_config_files.length}`);let s=i.length,a=await xf(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await oa(e,Do(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await kt(e),d=l===null?null:await ia(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await tt(l??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:_}=Pd(f);p.length>0&&i.push(`validate_merge_decisions_unreviewed:${p.length}`),IO(i,u.invalid_evidence_count);let y=s>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:y,ok:y==="ok",details:{...o,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),lossless_merge_receipt_count:_.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(_.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function st(e,t,n){n&&$I(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function RO(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let o=XI(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,st(t,o,n)}if(e.requestedChecks.has("resolution")){let o=JI(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,st(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=vO(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,st(t,o,n),st(t,eO(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await EO(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,st(t,o,n)}return e.requestedChecks.has("command_references")&&st(t,await SO(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await Wm(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,AO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await OO(e.pmRoot,e.items,ue(e.settings,Y()).type_to_folder,e.settings),n),t}function NO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...sf(t.closeReasonBackfillRows)),r.push(...of(t.resolutionBackfillRows)),r.push(...af(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...cf(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...lf(t.staleLinkPruneRows)),r}async function DO(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=NO(e,t,n),{applicable:a,gated:c}=uf(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await CO(a,o,i);d.push(...f.applied.map(lr)),u.push(...f.failed.map(({fix:p,error:_})=>({...lr(p),error:_ instanceof Error?_.message:String(_)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,p)=>f.localeCompare(p)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(lr),applied_fixes:d,gated_fixes:c.map(f=>({...lr(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function a_(e,t,n={}){Dl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new h("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",g.USAGE);let o=df(e.fixScope),i=re(process.cwd(),t.path);await Oe(i);let s=await te(i),a=On(s.schema),c=ue(s,Y()),l=jI(e),d=[],u=await Vm({includeBody:l.has("history_drift")||l.has("metadata"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let W=await Om(i);W.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${W.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=EI(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=AI(p,f,s.validation.metadata_required_fields),y=vI(s),b=kI(e.dependencyCycleSeverity),E=TI(e.parentCycleSeverity),v=II(e.scanMode),C=OI(i),k=await RO({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:C,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:y,dependencyCycleSeverity:b,parentCycleSeverity:E,fileScanMode:v,initialWarnings:[...new Set(d)]}),S=r?await DO(e,k,s,o,t,n):void 0,P=[...new Set(k.warnings)].sort((W,J)=>W.localeCompare(J)),L={ok:!k.checks.some(W=>W.status==="error"),has_warnings:P.length>0,checks:k.checks,warnings:P,...S!==void 0?{fixes:S}:{},generated_at:q(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?L:{...wI(L),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var c_=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d85d220-dad2-5234-8819-65632275eb47")}catch{}})();var PO=4;async function LO(e){try{return{status:"fulfilled",value:await ha(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function MO(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function FO(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.force?e.pendingReceipts:e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>$s(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function $O(e,t){let n=e.dryRun===!0,r=re(process.cwd(),t.path),o=await kt(r),i=await tt(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(i.invalid_evidence_count>0)throw new h(`Merge reconciliation refused ${i.invalid_evidence_count} invalid receipt evidence file(s).`,g.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let s=i.receipts,a=new Map;for(let k of s){let S=a.get(k.item_id)??[];S.push(k),a.set(k.item_id,S)}let c=Object.fromEntries([...a].map(([k,S])=>[k,{merge:{receipts:S.map(We)}}])),l=Object.fromEntries([...a].map(([k,S])=>[k,{gitWorkspaceRoot:o,receipts:S}])),d=await tf({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:c,...s.length>0?{mergeReceiptProofById:l}:{}},t),u=new Set(d.streams.map(k=>k.id)),f=[...a.keys()].filter(k=>!u.has(k)),p=await c_(f,PO,k=>LO({id:k,dryRun:n,options:e,global:t,auditContext:c[k],mergeReceiptProof:l[k]}));MO({receiptOnlyIds:f,results:p,repair:d});let _=await FO({dryRun:n,force:e.force===!0,pendingReceipts:s,repair:d,gitWorkspaceRoot:o}),y=await a_({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),b=y.checks.every(k=>k.status==="ok"),E=n?s.length===0:_===s.length,v=d.totals.failed===0&&b&&E,C=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:v?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:v,dry_run:n,repair:d,receipts:{pending_before:s.length,reconciled:_,summaries:s.map(We)},validation:y,guidance:C,generated_at:y.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a17e896-d54a-5796-8be3-535179c4d6e0")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00dc29ff-60e0-5755-b7f1-4f69e438e87f")}catch{}})();export{yd as ITEM_LATEST_TIMESTAMP_FIELDS,hd as ITEM_UNION_COLLECTION_FIELDS,Xs as MERGE_DRIVER_ARTIFACT_VALUES,na as PM_GITATTRIBUTES_END,Qn as PM_GITATTRIBUTES_START,Oo as PM_GITATTRIBUTES_V2_END,Wt as PM_GITATTRIBUTES_V2_START,oa as auditMergeAttributeFence,ia as auditMergeDriverConfiguration,No as buildMergeAttributePatterns,kt as findGitWorkspaceRoot,tt as inspectMergeReceiptEvidence,Ik as installMergeFence,Dd as listMergeReceipts,$s as markMergeReceiptReconciled,Is as mergeHistoryStreams,Rs as mergeItemDocuments,Ns as mergeJsonDocuments,Os as mergeRelationshipEventStreams,xk as refreshMergeAttributeFenceIfInstalled,pu as resolveMergeInstallContext,Do as resolveProjectMergeTypeFolders,hk as runMergeDriver,Ck as runMergeInstall,Nv as runMergeReceiptEvidenceReport,Rv as runMergeReceiptReport,$O as runMergeReconcile,We as summarizeMergeReceipt};
|
|
112
|
+
release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE id = ?").run(n.id),e.prepare("INSERT INTO item_search(id, title, description, tags) VALUES (?, ?, ?, ?)").run(n.id,n.title,n.description,n.tags.join(" "));let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function Ig(e){let t=td(e.pmRoot),n=Tg();if(!n){await Yn.rm(t,{force:!0});return}await Yn.mkdir(Sg.dirname(t),{recursive:!0});let r=`${t}.${OR()}.tmp`,o;try{o=new n(r),LR(o),o.exec("BEGIN IMMEDIATE"),js(o,"version",xg),js(o,"context_fingerprint",e.contextFingerprint),js(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Ag(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Yn.rm(t,{force:!0}),await Yn.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Yn.rm(r,{force:!0})]),i}}function MR(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Cg(e){let t=Tg();if(!t)return!1;let n=td(e.pmRoot),r;try{await Yn.access(n),r=new t(n),r.exec("PRAGMA foreign_keys = ON");let o=MR(r);if(o.version!==xg||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return r.close(),!1;r.exec("BEGIN IMMEDIATE");let i=r.prepare("DELETE FROM items WHERE relative_path = ?"),s=r.prepare("SELECT id FROM items WHERE relative_path = ?"),a=r.prepare("DELETE FROM item_search WHERE id = ?");for(let c of e.deletedRelativePaths??[]){let l=s.get(c);i.run(c),l&&a.run(l.id)}return e.row&&Ag(r,e.row),js(r,"source_cursor",e.sourceCursor),r.exec("COMMIT"),r.close(),!0}catch{try{r?.exec("ROLLBACK")}catch{}return r?.close(),!1}}async function Us(e){await Yn.rm(td(e),{force:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var St=8,od=500,FR="metadata-derived-index",jR="metadata-cache.json",UR="metadata-cache-bodies.json",zR="metadata-cache-collections.json",HR="metadata-cache-delta.json",qR="metadata-cache-manifest.json",Og=4,BR=["comments","notes","learnings","files","tests","test_runs","docs"];function Lg(){return pt(K())}function Hs(e){let t={...e},n={};for(let r of BR)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Mg(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function $g(e,t,n,r){let o=$R("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function qs(e){return ie.join(e,"runtime",jR)}function Bs(e){return ie.join(e,"runtime",UR)}function Gs(e){return ie.join(e,"runtime",zR)}function id(e){return ie.join(e,"runtime",HR)}function sd(e){return ie.join(e,"runtime",qR)}function Vs(e,t){let n=ie.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var GR=24,ct=new Map,Ws=new WeakMap;function ad(e){return Ws.get(e)??e.source_cursor}function VR(e,t){let n=ad(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Ws.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function WR(e,t){if(!e)return;let n=ad(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Ws.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function KR(e,t){if(!e)return;let n=ad(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){Ws.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function JR(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(VR(e,r),WR(t,r),KR(n,r))}function nd(e,t){ct.size>=GR&&!ct.has(e)&&ir(ct),ct.set(e,t)}async function gn(e,t){let n;try{n=await Ce.stat(e)}catch{return ct.delete(e),null}let r=ct.get(e);if(r&&No(r.signature,n.mtimeMs,n.ctimeMs,n.size))return ct.delete(e),ct.set(e,r),r.envelope;let o;try{o=t(await Ce.readFile(e,"utf8"))}catch{o=null}return nd(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function YR(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==St||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=qs(e),i=await gn(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await gn(Vs(o,t),r);return s===null&&Lo(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function XR(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==St||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Bs(e),o=await gn(r,n);return t&&o?.context_fingerprint!==t?await gn(Vs(r,t),n):o}async function ZR(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==St||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Gs(e),o=await gn(r,n);return t&&o?.context_fingerprint!==t?await gn(Vs(r,t),n):o}async function Fg(e){let t=id(e),n=await gn(t,r=>{let o=JSON.parse(r);return o.version!==St||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await Ce.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function jg(e){let t=sd(e),n=await gn(t,r=>{let o=JSON.parse(r);return o.version!==St||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await Ce.stat(t),await Do(e)}catch{}return null}async function Po(e,t){await Ce.mkdir(ie.dirname(e),{recursive:!0}),await H(e,JSON.stringify(t));try{let r=await Ce.stat(e);nd(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{ct.delete(e)}let n=ie.dirname(ie.dirname(e));if(e===qs(n)||e===Bs(n)||e===Gs(n)){let r=Vs(e,t.context_fingerprint);await H(r,JSON.stringify(t));try{let c=await Ce.stat(r);nd(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{ct.delete(r)}let o=ie.dirname(e),i=ie.extname(e),s=ie.basename(e,i),a=(await Ce.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==ie.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>ie.join(o,c.name));if(a.length>Og){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await Ce.stat(l)).mtimeMs}}catch{return null}}))).filter(l=>l!==null);for(let l of c.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,c.length-Og)))await Ce.rm(l.path,{force:!0}),ct.delete(l.path)}}}function QR(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Ug(e,t,n){return e===void 0||QR(e,t,n)}function Lo(e,t){e&&!e.includes(t)&&e.push(t)}function No(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function e0(e,t,n){let r=ie.join(e,t);try{let o=await Ce.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!j(o)&&Lo(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function t0(e,t){try{let n=await Ce.stat(ie.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function rd(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await t0(e,n))))}function zs(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&No(o,r.mtime_ms,r.ctime_ms,r.size)})}function n0(e){return Nt.some(t=>e.toLowerCase().endsWith(t))}function r0(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function o0(e,t,n){if(n)for(let r of await Ue({path:e,scope:"project"}))Lo(t,r)}function Rg(e,t,n,r){if(e)return t&&n?n.collections:r}async function i0(e,t,n){let r=await Ce.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=pr(e);await o0(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&No(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&No(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&No(f,o,i,s);if(!(!l||n.includeBody&&!u||n.includeCollections&&!p))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Rg(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let g=await Ce.readFile(e,"utf8"),y=$e(g,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:v=>Lo(n.warnings,v)}),b=Hs(y.metadata);return r0(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:b.light,heavyMetadata:Rg(n.includeCollections,p,f,b.heavy),bodyLength:l?c.body_length:y.body.length,body:n.includeBody?y.body:void 0}}function s0(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?Mg(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};Ug(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function a0(e,t,n,r){try{let o=await i0(t,n,r);s0(t,n,r,o)}catch{Lo(r.warnings,`item_list_item_read_failed:${e}/${ie.basename(t)}`)}}function c0(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function l0(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function d0(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function u0(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function f0(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!n0(s))continue;let a=ie.join(o,s),c=ie.relative(t.pmRoot,a);n.push(a0(r,a,c,t))}return n}async function p0(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!zs(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Po(qs(e.pmRoot),{version:St,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Po(sd(e.pmRoot),{version:St,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let n=[...e.state.documentsById.values()].map(({candidate:r})=>({relativePath:ie.relative(e.pmRoot,r.item_path),metadata:Hs(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Ig({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Us(e.pmRoot)}catch{}}async function m0(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await Po(Bs(e.pmRoot),{version:St,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function _0(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await Po(Gs(e.pmRoot),{version:St,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Ks(e,t,n={}){let r=await jg(e);return n.required!==!0&&(r===null||r.entry_count<od)?async()=>{}:ke(e,FR,30,t,!1,!1,3e3)}function Ng(e,t){let n=ie.relative(e,t);return n===""||n===".."||n.startsWith(`..${ie.sep}`)||ie.isAbsolute(n)?null:n}async function Do(e){await Promise.all([qs(e),Bs(e),Gs(e),id(e),sd(e)].map(async t=>{await Ce.rm(t,{force:!0}),ct.delete(t)})),await Us(e)}async function g0(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await Ce.stat(e.mutation.itemPath),n=Hs(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function h0(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function Js(e){let t=Ng(e.pmRoot,e.itemPath),n=e.previousItemPath?Ng(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Do(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=$g(e.preferredFormat,e.typeToFolder,e.schema,Lg()),o=await jg(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await Fg(e.pmRoot);if(s.invalid)return await Do(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=h0(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await g0({mutation:e});let l=Pg();return await Po(id(e.pmRoot),{version:St,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await rd(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Cg({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:Hs(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Us(e.pmRoot),[]}catch{return await Do(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function y0(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function Dg(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function w0(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function b0(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=pr(n);if(!o)continue;let i=e.includeCollections?Mg(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Ug(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:ie.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function v0(e){return e.forceSourceScan||rs()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!zs(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Dg(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Dg(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&w0(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Mo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Lg(),l=$g(t,n,o,c),d=await Fg(e);d.invalid&&await Do(e);let u=await YR(e,l,i.cacheDiagnostics),f=s?await XR(e,l):null,p=a?await ZR(e,l):null;JR(u,f,p,d.envelope);let m=c0(u,l),g=l0(f,l),y=d0(p,l),b=[...new Set(Object.values(n))],v=await rd(e,b),A=Object.keys(m),I=Math.max(1,Math.floor(i.derivedIndexMinimumItems??od));if(v0({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:v,entryKeys:A,minimumIndexedItems:I,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:y}))return b0({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:m,previousBodies:g,previousCollections:y});let x=await Promise.all(b.map(ee=>e0(e,ee,r))),P=rs(),S=u0(),E={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:P,previousEntries:m,previousBodies:g,previousCollections:y,state:S};await Promise.all(f0(x,E));let $=await rd(e,b),Q=zs(v,$)?$:{},R=S.misses.metadata||Object.keys(m).length!==Object.keys(S.newEntries).length||!zs(u?.directory_signatures,Q)||u===null?Pg():u.source_cursor;return await p0({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingCache:u,previousEntries:m,directorySignatures:Q,state:S,minimumIndexedItems:I}),s&&await m0({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingBodyCache:f,previousBodies:g,state:S}),a&&await _0({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingCollectionsCache:p,previousCollections:y,state:S}),y0(S)}async function zg(e,t,n,r,o){return(await Mo(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}async function Hg(e,t,n,r,o){return(await Mo(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function E0(e){try{return await $o.access(e),!0}catch{return!1}}function S0(e,t){e&&(e.includes(t)||e.push(t))}function x0(e){return e??pt(K())}function T0(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ze(e,t,n="pm-",r,o=Oe){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=_n(t,n),c=Cr(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=T0(r);for(let f of l)for(let[p]of d)for(let m of u){let g=fr(e,p,f,m,o);if(await E0(g))return{id:f,type:p,itemPath:g,item_format:m}}return null}async function He(e,t={}){let n=await $o.readFile(e.itemPath,"utf8");await Ue({path:e.itemPath,scope:"project"});let r=$e(n,{format:e.item_format,schema:t.schema,extensionFieldNames:x0(t.extensionFieldNames),onWarning:o=>S0(t.warnings,o)});return{raw:n,document:r}}async function Fo(e,t,n=Oe,r,o){return await Ir(e),(await zg(e,t,n,r,o)).map(s=>s.metadata)}async function jo(e,t,n=Oe,r,o){return await Ir(e),(await Hg(e,t,n,r,o)).map(s=>s.metadata)}async function Xn(e,t,n=Oe,r,o,i={}){return await Ir(e),(await Mo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function qg(e){return{async get(t){let n=await Ze(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await He(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>Fo(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function A0(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await $o.readdir(k0.join(e,o));for(let s of i)for(let a of Nt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function I0(e,t,n,r){let o=_n(t,n),i=await A0(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:ht(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function Bg(e,t,n,r){let o=await I0(e,t,n,r),i=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return o.length>0&&i.unshift(`Did you mean one of: ${o.join(", ")}?`),new w(`Item ${t} not found`,h.NOT_FOUND,{nextSteps:i})}function C0(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function O0(e){let t=e.typeToFolder??de(e.settings,K()).type_to_folder,n=await Ze(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Bg(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await ke(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let o=[],{raw:i,document:s}=await He(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=Kc(e.author),d=fn(e.settings);if(a&&c!==l&&!e.force&&!C0(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new w(`Item ${n.id} is assigned to ${a}. Use --force to override.`,h.CONFLICT);d.ownership_enforcement==="warn"&&o.push(`ownership_warning:assignee_conflict:${n.id}:${a}`)}return{typeToFolder:t,located:n,originalRaw:i,document:s,warnings:o,releaseLock:r}}catch(o){throw await r(),o}}function R0(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function N0(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await H(e.originalItemPath,e.originalRaw),await $o.rm(e.effectiveTargetItemPath,{force:!0});return}await H(e.originalItemPath,e.originalRaw)}}async function D0(e){let t=await O0({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a}=t;try{let c=Ke(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=Ke(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=await e.mutate(l);if(e.skipNoop===!0&&d.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...d.warnings??[]]};let u=e.resolveHistoryContext?.();l.metadata.updated_at=F();let f=Ke(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Dc({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:qg({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await ed({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),m="toon",g=xn(f,{format:m,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),y=fr(e.pmRoot,f.metadata.type,r.id,m,n),b=gt(e.pmRoot,r.id),v=await yt("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:y,history_path:b,item_format:m,before:c,after:f,contents:g}),{effectiveTargetItemPath:A,effectiveSerializedAfter:I,skipItemWrite:x}=R0(v,y,g),P=await Ks(e.pmRoot,e.author),S=[];try{x||await H(A,I),!x&&A!==r.itemPath&&await $o.rm(r.itemPath);let $=ho({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await ws(b,$)}catch(Q){throw await N0({skipItemWrite:x,effectiveTargetItemPath:A,originalItemPath:r.itemPath,originalRaw:o}),Q}x||(S=await Js({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:A,previousItemPath:r.itemPath,document:f}))}finally{await P()}let E=[...await je({path:A,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await je({path:b,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields})];return Nc({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:ns(c.metadata,d.changedFields),current:ns(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...v.warnings,...S,...E]}}finally{await a()}}async function Uo(e){return D0(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();var P0=3e4;function zo(e,t,n=P0){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Ho(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function L0(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${ne(t)})`}}async function Ys(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${ne(o)}`)}if(!r.ok){let o=await L0(r),i=o.length>0?`: ${o}`:"";throw new Error(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${ne(o)}`)}}finally{clearTimeout(n)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();function cd(e,t){let n=q(e);if(!n)return"unconfigured";let r=q(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function M0(e){let t=Vr(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function Vg(e){let t=e.search?.embedding_model;return q(t)||null}function $0(e){let t=q(e.providers?.openai?.base_url),n=q(e.providers?.openai?.model);if(!t||!n)return null;let r=Vg(e),o=q(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function F0(e){let t=q(e.providers?.ollama?.base_url),n=q(e.providers?.ollama?.model);if(!t||!n)return null;let r=Vg(e);return{name:"ollama",base_url:t,model:r??n}}function Wg(e){let t=(Array.isArray(e)?e:[e]).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function j0(e){let t=[],n=[],r=new Map;for(let o of e){let i=r.get(o);if(i===void 0){let s=t.length;t.push(o),r.set(o,s),n.push(s);continue}n.push(i)}return{uniqueInputs:t,originalToUniqueIndex:n}}function U0(e){let t=e.map((r,o)=>({embedding:r.embedding,index:r.index,position:o}));if(t.some(r=>r.index!==void 0)){for(let r of t)if(!Number.isInteger(r.index))throw new TypeError(`OpenAI embedding response entry at position ${r.position} is missing a valid integer index`);return[...t].sort((r,o)=>{let i=r.index-o.index;return i!==0?i:r.position-o.position})}return t}function qo(e){let t=$0(e),n=F0(e),r=[t,n].filter(a=>a!==null),o=q(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(a=>a.name===i):void 0)??r[0]??null,available:r}}function Gg(e){let t=Vr(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:M0(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function z0(e,t){let n=Wg(t);return e.name==="openai"?{target:Gg(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:n.length===1?n[0]:n}}:{target:Gg(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function H0(e,t){if(e.name==="openai"){let o=t.data;if(!Array.isArray(o)||o.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return U0(o).map((s,a)=>{let c=s.embedding;if(!cr(c))throw new Error(`OpenAI embedding response entry at index ${a} is missing a numeric embedding vector`);return[...c]})}let n=t.embedding;if(cr(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!cr(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function Kg(e,t,n={}){let r=zo(n.timeout_ms,"Embedding request"),o=Ho(n.fetcher,"Embedding request"),i=Wg(t),s=j0(i),a=z0(e,s.uniqueInputs),c=await Ys({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),l=H0(e,c);if(l.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${l.length}`);return s.originalToUniqueIndex.map(d=>[...l[d]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();var Xs=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function ld(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...Xs];let n=new Set(Xs),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...Xs]}var q0=8e3,dd=3200,Zn="...[semantic corpus truncated]",B0="search_embedding_corpus_max_characters_invalid:using_provider_default";function Tt(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function G0(e){return(e.reminders??[]).map(t=>Tt([t.at,t.text]))}function V0(e){return(e.events??[]).map(t=>Tt([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function W0(e){let t=(e.plan_steps??[]).map(s=>Tt([s.order,s.id,s.title,s.body,s.status,s.owner,s.evidence,s.blocked_reason,s.superseded_by,(s.linked_items??[]).map(a=>Tt([a.kind,a.id,a.note])).join(" "),(s.files??[]).map(a=>Tt([a.path,a.note])).join(" "),(s.tests??[]).map(a=>Tt([a.command,a.path,a.note])).join(" "),(s.docs??[]).map(a=>Tt([a.path,a.note])).join(" ")])),n=(e.plan_decisions??[]).map(s=>Tt([s.decision,s.rationale,s.evidence,s.step_id])),r=(e.plan_discoveries??[]).map(s=>Tt([s.text,s.step_id])),o=(e.plan_validation??[]).map(s=>Tt([s.text,s.command,s.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(s=>s!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function xt(e){return typeof e=="string"&&e.trim().length>0}var K0={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>xt(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>xt(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>xt(e.metadata.goal)?e.metadata.goal:void 0,value:e=>xt(e.metadata.value)?e.metadata.value:void 0,why_now:e=>xt(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>xt(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>xt(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>xt(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>xt(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>xt(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>(e.metadata.comments??[]).map(t=>t.text),notes:e=>(e.metadata.notes??[]).map(t=>t.text),learnings:e=>(e.metadata.learnings??[]).map(t=>t.text),reminders:e=>G0(e.metadata),events:e=>V0(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>W0(e.metadata)};function Jg(e,t={}){let n=t.fields??Xs,r={};for(let o of n){let i=K0[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function J0(e){return e?.trim().toLowerCase()==="ollama"?dd:q0}function Or(e,t){let n=J0(e),r=kf(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:B0}}function ud(e,t={}){let n=JSON.stringify(Jg(e,{fields:t.fields})),r=Or(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=Zn.length)return Zn.slice(0,r);let o=Math.max(0,r-Zn.length);return`${n.slice(0,o)}${Zn}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();function Y0(e,t){let n=e.search.embedding_batch_size,r=e.search.embedding_timeout_ms,o=e.search.scanner_max_batch_retries,i=Number.isFinite(n)&&n>0?Math.floor(n):1,s=Number.isFinite(r)&&r>0?Math.floor(r):3e4,a=Number.isFinite(o)&&o>=0?Math.floor(o):0;return{batchSize:i,timeoutMs:s,maxRetries:a,maxBatchInputCharacters:Number.POSITIVE_INFINITY,maxInputCharacters:t}}function X0(e,t,n){let r=[],o=[],i=0;for(let s of e){let a=o.length>=t,c=o.length>0&&Number.isFinite(n)&&i+s.length>n;(a||c)&&(r.push(o),o=[],i=0),o.push(s),i+=s.length}return r.push(o),r}function Z0(e,t){return e.name!=="ollama"?t:{...t,maxBatchInputCharacters:dd}}function Q0(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-Zn.length);return`${e.slice(0,n)}${Zn}`.slice(0,t)}function Yg(e){let t=ne(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function eN(e,t,n,r,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${ne(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${n} timeout_ms=${r}`;return Yg(i)?`${s} (${a}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`:`${s} (${a})`}async function fd(e,t,n,r,o,i){let s=null;for(let a=0;a<=o;a+=1)try{let c=await Kg(e,t,{timeout_ms:r});return a>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${n}:attempt=${a+1}:size=${t.length}`),c}catch(c){if(s=c,Yg(c)&&t.length>1){let l=Math.ceil(t.length/2),d=t.slice(0,l),u=t.slice(l);return i.push(`search_embedding_batch_split_after_timeout:batch=${n}:size=${t.length}:parts=${d.length}|${u.length}`),[...await fd(e,d,`${n}.1`,r,o,i),...await fd(e,u,`${n}.2`,r,o,i)]}if(a<o){let l=Math.min(1e3*2**a,8e3);await new Promise(d=>setTimeout(d,l))}}throw new Error(eN(e,n,t.length,r,o+1,s))}async function pd(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=[],i=Or(e.name,t.search.embedding_corpus_max_characters);i.warning&&o.push(i.warning);let s=Z0(e,Y0(t,i.maxCharacters)),a=0,c=n.map(f=>{let p=Q0(f,s.maxInputCharacters);return p.length<f.length&&(a+=1),p});a>0&&o.push(`search_embedding_input_truncated:count=${a}:max_characters=${s.maxInputCharacters}`);let l=X0(c,s.batchSize,s.maxBatchInputCharacters),d=[],u=0;for(let f=0;f<l.length;f+=1){let p=l[f];r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"start"}),d.push(...await fd(e,p,String(f+1),s.timeoutMs,s.maxRetries,o)),u+=p.length,r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"complete"})}return{vectors:d,warnings:o}}import{spawnSync as Zg}from"node:child_process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}catch{}})();var tN="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",nN="PM_OLLAMA_MODEL",rN="http://localhost:11434",oN="qwen3-embedding:0.6b",iN=".agents/pm/search/lancedb/",sN=1500,aN=2500,cN=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,lN=/embed|embedding/i,At=q;function dN(){let e=At(process.env[tN]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Xg(e){return e.some(t=>At(t)!==null)}function uN(e){let t=At(e);return!!(t&&t.toLowerCase()!=="ollama")}function fN(e){let t=At(e);return!!(t&&t.toLowerCase()!=="lancedb")}function pN(e){return uN(e.search?.provider)||fN(e.vector_store?.adapter)||Xg([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Xg([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function mN(){let e=Zg("ollama",["--version"],{encoding:"utf8",timeout:sN});return e.error?!1:e.status===0}function _N(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;let n=t.map(i=>i.split(/\s+/)[0]?.trim()).filter(i=>!!(i&&i.length>0)).filter(i=>i.toUpperCase()!=="NAME");if(n.length===0)return null;let r=n.find(i=>cN.test(i));return r||(n.find(i=>lN.test(i))??null)}function gN(e){let t=At(e.providers?.ollama?.model);if(t)return t;let n=At(process.env[nN]);if(n)return n;let r=Zg("ollama",["list"],{encoding:"utf8",timeout:aN});if(!r.error&&r.status===0){let o=_N(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function hN(e){return{baseUrl:At(e.providers?.ollama?.base_url)===null,model:At(e.providers?.ollama?.model)===null,lancedbPath:At(e.vector_store?.lancedb?.path)===null,embeddingModel:At(e.search?.embedding_model)===null}}function yN(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function wN(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=rN),t.model&&(o.model=n)}function bN(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=iN}function vN(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function Rr(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(dN()||pN(e))return t;let n=hN(e);if(!yN(n)||n.model&&!mN())return t;let r=structuredClone(e),o=gN(r);return o?(wN(r,n,o),bN(r,n),vN(r,n,o),{settings:r,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${oN} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}catch{}})();import{mkdir as kN,readFile as EN,stat as gd,unlink as SN}from"node:fs/promises";import{basename as Qg,dirname as md,isAbsolute as xN,join as TN,resolve as hd}from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}catch{}})();var yd="pm_items",AN=/[^a-zA-Z0-9_-]/g,IN=128,CN=".pm-cli-local-vectors",_d=1,Nr=new Map;function wd(e){return(q(e.collection_name)??yd).replaceAll(AN,"_").slice(0,IN)}function eh(e){if(!cr(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function th(e){let t=q(e.result?.status);if(t)return{status:t};let n=q(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function nh(e,t,n,r,o){return await Ys({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function ON(e){let t=q(e.vector_store?.qdrant?.url);if(!t)return null;let n=q(e.vector_store?.collection_name),r=q(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==yd?{collection_name:n}:{},...r?{api_key:r}:{}}}function RN(e){let t=hd(e),n=md(t);return Qg(t)==="pm"&&Qg(n)===".agents"?md(n):t}function NN(e,t){return!t||xN(e)?e:hd(RN(t),e)}function DN(e,t){let n=q(e.vector_store?.lancedb?.path);if(!n)return null;let r=q(e.vector_store?.collection_name);return{name:"lancedb",path:NN(n,t),...r&&r!==yd?{collection_name:r}:{}}}function PN(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=q(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=eh(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function LN(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=q(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function MN(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function rh(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function bd(e,t){return Bo(e,t)}function Bo(e,t){return TN(hd(e),CN,`${t}.json`)}function $N(e,t,n){let r=q(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=eh(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function FN(e,t,n){let r;try{r=JSON.parse(n)}catch(c){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${ne(c)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==_d)throw new Error(`LanceDB local snapshot at '${e}' must include version=${_d}`);let i=q(r.table);if(!i)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(i!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${i}'`);let s=r.records;if(!Array.isArray(s))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let a=new Map;for(let c=0;c<s.length;c+=1){let l=$N(s[c],c,e);a.set(l.id,l)}return a}async function jN(e){try{let t=await gd(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!j(t))throw t;return null}}function UN(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Nr.set(e,{records:n,mtimeMs:null,size:null}),n}function zN(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function oh(e,t){let n=bd(e,t),r=Bo(e,t),o=await jN(r),i=Nr.get(n);if(!o){let a=UN(n,i);if(a)return a}if(zN(i,o))return i.records;let s=new Map;try{let a=await EN(r,"utf8");s=FN(r,t,a)}catch(a){if(!j(a))throw a}return Nr.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function HN(e){let t=[...e.values()];return t.sort((n,r)=>n.id.localeCompare(r.id)),t.map(n=>({id:n.id,vector:[...n.vector],...n.payload?{payload:n.payload}:{}}))}async function qN(e){try{await SN(e)}catch(t){if(!j(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${ne(t)}`)}}async function ih(e,t,n){let r=Bo(e,t);if(n.size===0){await qN(r);return}let o=md(r);try{await kN(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${ne(s)}`)}let i=`${JSON.stringify({version:_d,table:t,records:HN(n)})}
|
|
113
|
+
`;try{await H(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${ne(s)}`)}}function Go(e,t){let n=ON(e),r=DN(e,t),o=[n,r].filter(c=>c!==null),i=q(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(c=>c.name===s):void 0)??o[0]??null,available:o}}function sh(e){let t=wd(e);if(e.name==="qdrant"){let o=Vr(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function BN(e,t){let n=sh(e),r=PN(t);return e.name==="qdrant"?{target:n,method:"POST",headers:rh(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:wd(e),records:r}}}function GN(e,t){let n=sh(e),r=LN(t);return e.name==="qdrant"?{target:n,method:"POST",headers:rh(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:wd(e),ids:r}}}async function vd(e,t,n={}){let r=BN(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=bd(a.path,c.table),d=await oh(a.path,c.table);for(let p of c.records)d.set(p.id,p);await ih(a.path,c.table,d);let u=Bo(a.path,c.table),f=await gd(u);return Nr.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=zo(n.timeout_ms,"Vector request"),i=Ho(n.fetcher,"Vector request"),s=await nh(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return th(s)}async function kd(e,t,n={}){let r=GN(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=bd(a.path,c.table),d=await oh(a.path,c.table);if(d.size===0)return{status:"ok"};for(let u of c.ids)d.delete(u);if(await ih(a.path,c.table,d),d.size===0)Nr.delete(l);else{let u=Bo(a.path,c.table),f=await gd(u);Nr.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=zo(n.timeout_ms,"Vector request"),i=Ho(n.fetcher,"Vector request"),s=await nh(MN(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return th(s)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}catch{}})();function Dr(e,t){let n=q(e),r=q(t);return!n||!r?null:{provider:n,model:r}}function ah(e){if(e==null)return null;if(typeof e!="object"||Array.isArray(e))throw new Error("Vectorization embedding metadata must be an object when set");let t=Dr(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function Ed(e,t){if(!Number.isInteger(t)||t<=0)throw new Error("Vectorization embedding metadata requires a positive vector dimension");return{provider:e.provider,model:e.model,vector_dimension:t}}function Vo(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Sd(e,t){return!!(e&&e.vector_dimension!==t)}function xd(e,t){if(e.length===0)throw new Error(`${t} returned no vectors`);let r=e[0].length;if(!Number.isInteger(r)||r<=0)throw new Error(`${t} returned an empty vector`);for(let o=1;o<e.length;o+=1)if(e[o]?.length!==r)throw new Error(`${t} returned mixed vector dimensions`);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();var dh="search/vectorization-status.json";function Ko(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function uh(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function fh(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!uh(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Jo(e){let t=lh.join(e,dh),n=await Z(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.items){if(typeof s!="object"||s===null)return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let a=s.id,c=s.updated_at;if(typeof a!="string"||a.trim().length===0||!uh(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=ah(r.embedding)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}return{entries:Object.fromEntries([...o.entries()].sort((s,a)=>s[0].localeCompare(a[0]))),embedding:i,warnings:[]}}async function ph(e,t,n){let r=fh(t),o=lh.join(e,dh),i=`${JSON.stringify({version:1,generated_at:F(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
|
|
114
|
+
`;await H(o,i)}function WN(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function KN(e){let t=Dr(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function Wo(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function JN(e,t,n){if(!n.settings&&!await U(be(e)))return Wo(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await pn(e),c=a.warnings.find(l=>l.startsWith("settings_read_"));if(c)return Wo(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return Wo(t,`search_semantic_refresh_skipped:settings_read_failed:${ne(a)}`)}let o=n.apply_runtime_defaults?Rr(r).settings:r,i=qo(o).active;if(!i)return Wo(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=Go(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:Wo(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function YN(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,l=[];for(let d of r){let u=await Ze(e,d,t,n,o);if(!u){c.add(d);continue}try{let f=await He(u,{schema:i});l.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${ne(f)}`)}}return l.sort((d,u)=>d.id.localeCompare(u.id)),{documents:l,missingIds:Ko(c),skippedIds:Ko(a),warnings:s}}async function XN(e,t,n){let r=Or(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=ld(e),i=n.map(a=>ud(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await pd(t,e,i);return{vectors:s.vectors,vector_dimension:xd(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function ZN(e,t,n){return await vd(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:WN(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function QN(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await kd(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${ne(n)}`]}}}async function mh(e,t,n={}){let r=Ko(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await JN(e,r,n);if(!("settings"in o))return o;let i=de(o.settings,K()),s=await YN(e,o.settings.id_prefix,o.settings.item_format,r,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Jo(e):{entries:{},embedding:null,warnings:[]},c=KN(o.provider),l=a.entries,d={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Vo(a.embedding,c))d={refreshed:[],skipped:s.documents.map(y=>y.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let y=await XN(o.settings,o.provider,s.documents);if(Sd(a.embedding,y.vector_dimension))d={refreshed:[],skipped:s.documents.map(b=>b.id),warnings:[...y.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=Ed(c,y.vector_dimension);let b=await ZN(o.vectorStore,s.documents,y.vectors);d={refreshed:b.refreshed,skipped:b.skipped,warnings:[...y.warnings,...b.warnings]}}}catch(y){d={refreshed:[],skipped:s.documents.map(b=>b.id),warnings:[`search_semantic_refresh_failed:${ne(y)}`]}}let f=await QN(o.vectorStore,s.missingIds),p=new Set(d.refreshed),m=Object.fromEntries(s.documents.filter(y=>p.has(y.id)).map(y=>[y.id,y.document.metadata.updated_at])),g=[];if(Object.keys(m).length>0||s.missingIds.length>0){let y={...l,...fh(m)};for(let b of s.missingIds)delete y[b];try{await ph(e,y,u)}catch(b){g.push(`search_vectorization_status_ledger_write_failed:${ne(b)}`)}g.push(...a.warnings)}return{refreshed:Ko([...d.refreshed,...f.refreshed]),skipped:Ko([...s.skippedIds,...d.skipped,...f.skipped]),warnings:[...s.warnings,...d.warnings,...f.warnings,...g]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="412fc2d2-daee-5d87-82ab-5411a1503087")}catch{}})();function Td(e,t){let n=t??{};return e.filter(r=>n[r.id]!==r.updated_at).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}import rD from"node:crypto";import Id from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var M8=new Map([[h.USAGE,"invalid_command_usage"],[h.NOT_FOUND,"item_not_found"],[h.CONFLICT,"lock_conflict"],[h.DEPENDENCY_FAILED,"dependency_failed"]]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var J8=Id.join("runtime","telemetry","events.jsonl"),Y8=Id.join("runtime","telemetry","state.json"),X8=Id.join("runtime","telemetry","otel-spans.jsonl");var gh=1;var hh=15;var Z8=3600*1e3;var Q8=globalThis.fetch,Cd=["user","automation","test","dogfood"],e9=Promise.resolve(),t9=Promise.resolve();var n9=new Set(Cd);var r9=rD.randomUUID();var yh="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",o9=new RegExp(`\\b(${yh})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),i9=new RegExp(`(--${yh})(=|\\s+)([^\\s,;]+)`,"giu");(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e57e03e-3c60-5c1b-b455-9318df8027f6")}catch{}})();var oD=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function Od(e){if(typeof e!="string")return;let t=e.trim();for(let n of oD)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Rd(e){let t={};for(let n of e){let r=Od(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function wh(e){return Object.values(Rd(e))}import kh from"node:fs/promises";import{createRequire as iD}from"node:module";import Qe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c21b1a94-1d80-57c0-b090-c4831fc505a2")}catch{}})();function bh(e,t){let n=Qe.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Qe.sep}`)&&!Qe.isAbsolute(n))return n.split(Qe.sep).join("/");let r=Qe.resolve(e),o=0xcbf29ce484222325n;for(let s=0;s<r.length;s+=1)o^=BigInt(r.charCodeAt(s)),o=BigInt.asUintN(64,o*0x100000001b3n);return`<external>/${o.toString(16).padStart(16,"0")}/${Qe.basename(Qe.dirname(e))}/package.json`}function sD(e){return e.includes(`${Qe.sep}.pnpm${Qe.sep}`)?"pnpm":e.includes(`${Qe.sep}node_modules${Qe.sep}`)?"npm":"other"}async function vh(e){try{let t=JSON.parse(await kh.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function Nd(e){try{return await kh.realpath(e)}catch{return Qe.resolve(e)}}async function Eh(e,t,n=Je(import.meta.url,["../../.."])){let r=await Nd(t),o=await Nd(Qe.join(n,"package.json")),i=await vh(o),s=new Map;i!==void 0&&s.set(o,{version:i,path:bh(o,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=iD(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await Nd(d),f=await vh(u);if(f===void 0)continue;let p=u,m=s.get(p);if(m){m.consumers.includes(l.name)||(m.consumers.push(l.name),m.consumers.sort((g,y)=>g.localeCompare(y)));continue}s.set(p,{version:f,path:bh(u,r),layout:sD(u),consumers:[l.name]})}catch{}let a=[...s.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=i===void 0?[]:a.filter(l=>l.version!==i);return{host_version:i??null,copies:a,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${i}:${l.version}:${l.consumers.join("+")}`)}}import lu from"node:fs/promises";import du from"node:path";import{Option as qY}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="411f4336-eb02-5167-9dce-ea99822a8a14")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function Sh(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Yo(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?Sh(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Sh(t):"root"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var aD={critical:0,high:1,medium:2,low:3,minimal:4},cD=Object.keys(aD),U9=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${cD.join(", ")}), case-insensitive`;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9581c92-5e8a-589d-9681-d4d014e6902b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="989b570c-112e-5ee3-8731-ab34f215ba45")}catch{}})();var r6=new Map(Na.map(e=>[e.toLowerCase(),e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}catch{}})();import{createRequire as dD}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var uD=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,m6=new RegExp(`\\b(${uD.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var _6=dD(import.meta.url);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e6ba316-b067-51df-abeb-c3e3488a504d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var fD=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],x6=new Map(fD.map(e=>[e.action,e]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ad30a32-0f83-5473-b0a3-349e271d8378")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dff9b113-2b29-5154-afbf-f191f2f556a6")}catch{}})();import pD from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();function Zs(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function mD(e,t){return[e.updated_at,t].map(r=>({value:r,time:Date.parse(r??"")})).filter(r=>typeof r.value=="string"&&Number.isFinite(r.time)).sort((r,o)=>o.time-r.time)[0]?.value??e.updated_at}function Th(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=Zs(t.in_progress_status),i=[];for(let s of e){if(Zs(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=mD(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let l=Math.max(0,Math.floor((r-c)/36e5));l>=n&&i.push({id:s.id,last_activity_at:a,age_hours:l})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:n,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Dd(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>Zs(String(o.status))===Zs(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await Mt(pD.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&r.set(o.id,s)})),Th(t,{...n,last_history_activity:o=>r.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var P6=Object.freeze({"<":"<",">":">",""":'"',"'":"'","&":"&"});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4ecab833-db06-5baa-bfe6-d28b4c97f85a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();import W6 from"node:readline/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aba5403c-0694-5c51-95a8-ae7e7575347b")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f56c4ef-58e1-5cf6-a10e-dfa29b9ad3e8")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be7e506f-c48f-5dfb-9fed-ba1e74fa60ff")}catch{}})();var Pd=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or pass title as the first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit item id (normalized with the configured id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Item type (built-ins plus any configured custom types)"},{target:"template",keys:["template"],option:"--template <value>",description:"Apply named create template defaults before explicit flags"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Create required-option policy mode: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Scheduling preset for Reminder|Meeting|Event: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Close reason when creating directly in a terminal status",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for a terminal imported item",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],Ah=Pd.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Ih=Pd.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Ld=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by dependency id or exact row signature (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append linked test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0}],Md=Ld.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Ch=Ld.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88009976-e03f-5a67-b6fc-bf60240dde49")}catch{}})();function Se(e){return e.map(t=>({...t}))}var $d=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],Oh=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],ID=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Oh],Rh=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],CD=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],OD=[...$d,...Rh],Nh=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],RD=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Dh=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],Fd=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...Se($d),...Se(ID),{param:"ids",flag:"--ids"},...Se(Rh),...Se(RD),...Se(Nh),...Se(Dh),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],jd=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...Se(OD)],Ud=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...Se($d),...Se(Oh),...Se(CD),...Se(Nh),...Se(Dh),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Ph=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],Qs=Se(Ph),Lh=[{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],zd=Se(Lh),Mh=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],Hd=Se(Mh),qd=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],Bd=Se(qd),Gd=Se(qd);var Vd=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],Wd=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4efc5934-7d1b-517b-8b5e-eb2fe14379f2")}catch{}})();function T(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function $h(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var X=T("id","item_id",!0),Xo=T("id","item_id",!1),Zo=T("text","string",!1),Qo=T("plan-id","item_id",!0),Fh=T("step","string",!0),DD=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],Kd=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],PD={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},Pr=[{command:"plan create",parent:"plan",action:"create",slots:[T("title","string",!1,{polymorphic:!0})],accepted_flags:DD,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[Qo],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[Qo],accepted_flags:Kd,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(PD).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[Qo,Fh],accepted_flags:Kd,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[Qo,Fh,T("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(e=>({command:`plan ${e}`,parent:"plan",action:e,slots:[Qo],accepted_flags:Kd,description:`${$h(e)} for one Plan item.`,example:`pm plan ${e} pm-a1b2`})),...["list","show","put","remove"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[T("kind","string",!0),...e==="list"?[]:[T("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${$h(e)} assurance declarations by kind.`,example:e==="list"?"pm assurance list measurement":`pm assurance ${e} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[T("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[T("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[T("preset","string",e==="apply")],accepted_flags:["--author","--message","--owner"],description:e==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:e==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[T("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[T("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[T("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[T("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[T("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],LD=[...Pr].sort((e,t)=>t.command.length-e.command.length),MD=new Map([["append",[X,Zo]],["assurance",[T("action","action",!0),T("kind","string",!1),T("id","string",!1)]],["beads import",[T("file","string",!1)]],["changelog export",[T("file","string",!1)]],["claim",[Xo]],["close",[X,Zo]],["close-task",[X,T("reason","string",!1)]],["comments",[X,Zo]],["completion",[T("shell","string",!1)]],["config",[T("scope","string",!1,{polymorphic:!0}),T("action","action",!1),T("key","string",!1),T("value","string",!1,{polymorphic:!0})]],["copy",[X]],["create",[T("type-or-title","string",!1,{polymorphic:!0}),T("title","string",!1)]],["delete",[X]],["deps",[X]],["docs",[X]],["event",[T("title","string",!0)]],["files",[X]],["files discover",[X]],["files lookup",[T("paths","string",!0,{variadic:!0})]],["focus",[Xo]],["get",[X]],["graph",[T("subcommand","action",!0),Xo,T("target","item_id",!1)]],["guide",[T("topic","string",!1)]],["history",[X]],["history-compact",[Xo]],["history-redact",[X]],["history-repair",[Xo]],["init",[T("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[X,T("reason","string",!1)]],["item reopen",[X,T("reason","string",!0)]],["learnings",[X,Zo]],["meet",[T("title","string",!0)]],["merge",[T("subcommand","action",!0),T("artifact","string",!1),T("base","string",!1),T("ours","string",!1),T("theirs","string",!1)]],["notes",[X,Zo]],["package",[T("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[T("target","string",!0)]],["package upgrade",[T("target","string",!1)]],["packages",[T("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[T("target","string",!0)]],["packages upgrade",[T("target","string",!1)]],["pause-task",[X]],["plan",[T("subcommand","action",!0),T("id","item_id",!1,{polymorphic:!0}),T("step","string",!1),T("new-order","integer",!1)]],["profile",[T("subcommand","action",!0),T("name","string",!1)]],["release",[X]],["remind",[T("title","string",!0)]],["restore",[X,T("target","string",!0)]],["schema",[T("subcommand","action",!0),T("name","string",!1)]],["search-advanced",[T("keywords","string",!0,{variadic:!0})]],["search",[T("keywords","string",!0,{variadic:!0})]],["start-task",[X]],["telemetry",[T("namespace-or-subcommand","action",!1,{polymorphic:!0}),T("subcommand","action",!1)]],["test",[X]],["update",[X]],["workspace snapshot",[T("action","action",!0),T("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("targets","string",!1,{variadic:!0})]])),["vcs abandon",[X]],["vcs create",[T("title","string",!0)]],["vcs merge",[X]],["vcs propose",[X]],["vcs ref-create",[T("name","string",!0)]],["vcs show",[X]]]);function $D(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function FD(e){let t=$D(e);return LD.find(n=>n.command===t||t.startsWith(`${n.command} `))}function V(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var jD=[...V("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...V("item","item","consolidation","pm-yql1",["append","claim","close","close-many","close-task","comments","copy","create","delete","docs","files","get","learnings","notes","pause-task","release","start-task","test","update","update-many"]),...V("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...V("list","list","target_noun","pm-pfqi",["list"]),...V("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...V("context","context","target_noun","pm-pbyu",["context"]),...V("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...V("search","search","target_noun","pm-pbyu",["search"]),...V("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...V("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...V("graph","graph","target_noun","pm-pbyu",["graph"]),...V("graph","graph show","consolidation","pm-yql1",["deps"]),...V("history","history","target_noun","pm-pbyu",["history"]),...V("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...V("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...V("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...V("workspace","workspace init","consolidation","pm-n7rr",["init"]),...V("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...V("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...V("package","package","package_owned","package:beads",["beads import"]),...V("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...V("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...V("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...V("ops","ops assurance","consolidation","pm-2tan",Pr.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...V("plan","plan","target_noun","pm-pbyu",["plan"]),...V("plan","plan","target_noun","pm-2tan",Pr.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...V("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...V("help","help","target_noun","pm-pbyu",["help"]),...V("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],UD=[...new Set(jD.map(({command:e})=>e))].map(e=>({command:e,slots:FD(e)?.slots??MD.get(e)??[]}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function Jd(e){return[...new Set(Array.from(e,t=>t.trim()).filter(t=>t.length>0))]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="789faf62-dfbf-56ff-9412-55adc5c12d3d")}catch{}})();var jh=oc.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),zD=[...jh,{flag:"--version"}],Uh=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--has-notes"},{flag:"--no-notes"},{flag:"--has-learnings"},{flag:"--no-learnings"},{flag:"--has-files"},{flag:"--no-files"},{flag:"--filter-files-missing"},{flag:"--has-docs"},{flag:"--no-docs"},{flag:"--filter-docs-missing"},{flag:"--has-tests"},{flag:"--no-tests"},{flag:"--has-comments"},{flag:"--no-comments"},{flag:"--has-deps"},{flag:"--no-deps"},{flag:"--has-body"},{flag:"--empty-body"},{flag:"--has-linked-command"},{flag:"--no-linked-command"}],zh=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--filter-has-notes"},{flag:"--filter-no-notes"},{flag:"--filter-has-learnings"},{flag:"--filter-no-learnings"},{flag:"--filter-has-files"},{flag:"--filter-no-files"},{flag:"--filter-has-docs"},{flag:"--filter-no-docs"},{flag:"--filter-has-tests"},{flag:"--filter-no-tests"},{flag:"--filter-has-comments"},{flag:"--filter-no-comments"},{flag:"--filter-has-deps"},{flag:"--filter-no-deps"},{flag:"--filter-has-body"},{flag:"--filter-empty-body"},{flag:"--filter-has-linked-command"},{flag:"--filter-no-linked-command"},{flag:"--ids",list:!0},{flag:"--limit"},{flag:"--offset"}],ta=eu([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--status",list:!0},{flag:"--all",value_type:"boolean"},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--today"},{flag:"--recent"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--ids",list:!0},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...Uh,{flag:"--limit"},{flag:"--offset"},{flag:"--after"},{flag:"--no-truncate"},{flag:"--compact"},{flag:"--brief"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--sort"},{flag:"--order"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--include-body"},{flag:"--strict-read"},{flag:"--format"},{flag:"--stream"}],new Set(["--limit","--token-budget","--offset","--after","--no-truncate","--compact","--brief","--full","--fields","--include-body","--strict-read"])),Hh=[{flag:"--group-by",list:!0},{flag:"--count"},{flag:"--completion"},{flag:"--sum"},{flag:"--avg"},{flag:"--include-unparented"},{flag:"--include_unparented"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0}],qh=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body","--text"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function eu(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var Bh=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note","--text"]},{flag:"--add-json"},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--since"},{flag:"--event-type"},{flag:"--include-meta"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Gh=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning","--text"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Vh=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--append-stable"},{flag:"--validate-paths"},{flag:"--scope"},{flag:"--limit"},{flag:"--offset"},{flag:"--no-truncate"},{flag:"--strict-read"},{flag:"--explain"},{flag:"--lines",value_name:"start:end"},{flag:"--decision-depth",value_name:"n",value_type:"number"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Wh=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--validate-paths"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Kh=[{flag:"--id",value_name:"item-id"},{flag:"--limit"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--diff"},{flag:"--field"},{flag:"--verify"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--format"}],Jh=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],Yh=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Xh=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Zh=[{flag:"--event",repeatable:!0},{flag:"--all-actionable"},{flag:"--dry-run"},{flag:"--plan-fingerprint"},{flag:"--limit",value_type:"number"},{flag:"--attributed-author",aliases:["--attributed_author"]},{flag:"--reviewer"},{flag:"--reason"}],Qh=[{flag:"--id",value_name:"item-id"},{flag:"--before"},{flag:"--ids",list:!0},{flag:"--all-over",value_type:"number"},{flag:"--closed"},{flag:"--all-streams"},{flag:"--min-entries",value_type:"number"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ey=[{flag:"--description"},{flag:"--default-status",aliases:["--default_status"]},{flag:"--folder"},{flag:"--alias"},{flag:"--role"},{flag:"--order"},{flag:"--type"},{flag:"--commands"},{flag:"--cli-flag"},{flag:"--required"},{flag:"--required-on-create"},{flag:"--no-allow-unset"},{flag:"--required-types"},{flag:"--infer"},{flag:"--min-count"},{flag:"--apply",value_type:"boolean"},{flag:"--to"},{flag:"--migration-id",aliases:["--migration_id"]},{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],ty=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],tu=[{flag:"--title"},{flag:"--description"},{flag:"--scope"},{flag:"--parent"},{flag:"--related"},{flag:"--blocks"},{flag:"--blocked-by",aliases:["--blocked_by"]},{flag:"--harness"},{flag:"--mode"},{flag:"--resume-context",aliases:["--resume_context"]},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--priority"},{flag:"--status",short:"-s"},{flag:"--create-mode",aliases:["--create_mode"]},{flag:"--deadline"},{flag:"--estimate",aliases:["--estimated-minutes","--estimated_minutes"]},{flag:"--acceptance-criteria",aliases:["--acceptance_criteria","--ac"],repeatable:!0},{flag:"--definition-of-ready",aliases:["--definition_of_ready"]},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now",aliases:["--why_now"]},{flag:"--assignee"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-reason",aliases:["--blocked_reason"]},{flag:"--unblock-note",aliases:["--unblock_note"]},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps",aliases:["--repro_steps"]},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--affected-version",aliases:["--affected_version"]},{flag:"--fixed-version",aliases:["--fixed_version"]},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact",aliases:["--customer_impact"]},{flag:"--comment",repeatable:!0},{flag:"--note",repeatable:!0},{flag:"--learning",repeatable:!0},{flag:"--reminder",repeatable:!0},{flag:"--event",repeatable:!0},{flag:"--type-option",aliases:["--type_option"],repeatable:!0},{flag:"--body"},{flag:"--claim"},{flag:"--from-search",aliases:["--from_search"]},{flag:"--template"},{flag:"--step-title",aliases:["--step_title"]},{flag:"--step"},{flag:"--step-body",aliases:["--step_body"]},{flag:"--step-owner",aliases:["--step_owner"]},{flag:"--step-status",aliases:["--step_status"]},{flag:"--step-evidence",aliases:["--step_evidence"]},{flag:"--step-blocked-reason",aliases:["--step_blocked_reason"]},{flag:"--step-replacement",aliases:["--step_replacement"]},{flag:"--depends-on",aliases:["--depends_on"]},{flag:"--link"},{flag:"--link-kind",aliases:["--link_kind"]},{flag:"--link-note",aliases:["--link_note"]},{flag:"--promote-to-item-dep",aliases:["--promote_to_item_dep"]},{flag:"--allow-multiple-active",aliases:["--allow_multiple_active"]},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--decision-text",aliases:["--decision_text","--decision"]},{flag:"--decision-rationale",aliases:["--decision_rationale"]},{flag:"--decision-evidence",aliases:["--decision_evidence"]},{flag:"--discovery-text",aliases:["--discovery_text","--discovery"]},{flag:"--validation-text",aliases:["--validation_text","--validation"]},{flag:"--validation-command",aliases:["--validation_command"]},{flag:"--validation-expected",aliases:["--validation_expected"]},{flag:"--depth"},{flag:"--field"},{flag:"--fields",list:!0},{flag:"--steps"},{flag:"--materialize-type",aliases:["--materialize_type"]},{flag:"--materialize-parent",aliases:["--materialize_parent"]},{flag:"--materialize-tags",aliases:["--materialize_tags"]},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ny=[{flag:"--id-prefix",aliases:["--prefix"]},{flag:"--preset"},{flag:"--type-preset"},{flag:"--defaults",short:"-y",aliases:["--yes"]},{flag:"--author"},{flag:"--agent-guidance"},{flag:"--with-packages"},{flag:"--no-merge-fence"},{flag:"--workspace"},{flag:"--force"},{flag:"--verbose"}],ry=[{flag:"--criterion"},{flag:"--clear-criteria"},{flag:"--format"},{flag:"--policy"},{flag:"--default-depth"},{flag:"--activity-limit"},{flag:"--stale-threshold-days"},{flag:"--section-hierarchy"},{flag:"--section-activity"},{flag:"--section-progress"},{flag:"--section-blockers"},{flag:"--section-files"},{flag:"--section-workload"},{flag:"--section-staleness"},{flag:"--section-tests"}],nu=[{flag:"--init"},{flag:"--scaffold"},{flag:"--capability"},{flag:"--install"},{flag:"--uninstall"},{flag:"--explore"},{flag:"--list"},{flag:"--manage"},{flag:"--describe"},{flag:"--markdown"},{flag:"--output"},{flag:"--reload"},{flag:"--watch"},{flag:"--doctor"},{flag:"--catalog"},{flag:"--adopt"},{flag:"--adopt-all"},{flag:"--activate"},{flag:"--deactivate"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"},{flag:"--detail"},{flag:"--trace"},{flag:"--runtime-probe"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],Ut=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],oy=[...Ut,{flag:"--capability"}],Yd=[...nu,{flag:"--declarative"}],HD=[...oy,{flag:"--declarative"}];var qD=[...Ut,{flag:"--markdown"},{flag:"--output"}];var BD=[...Ut,{flag:"--dry-run"}],GD=[...Ut,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],VD=[...Ut,{flag:"--watch"}],WD=[...Ut,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],KD=[...Ut,{flag:"--fields",list:!0}],JD=[...Ut,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],iy=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],sy=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var ay=[{flag:"--id",value_name:"item-id"},{flag:"--reason",value_name:"value"},{flag:"--close-reason",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--duplicate-of",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",aliases:["--expected_result","--expected"],value_name:"value"},{flag:"--actual-result",aliases:["--actual_result","--actual"],value_name:"value"},{flag:"--force",value_type:"boolean"}],cy=[{flag:"--filter-status",list:!0},{flag:"--filter-type"},{flag:"--filter-tag"},{flag:"--filter-priority"},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee"},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint"},{flag:"--filter-release"},...zh,{flag:"--reason"},{flag:"--completed-at"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--validate-close"},{flag:"--author"},{flag:"--message"},{flag:"--force"},{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"}],ly=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],dy=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"},{flag:"--if-available"},{flag:"--next"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee-filter"},{flag:"--parent"},{flag:"--sprint"},{flag:"--release"},{flag:"--max-attempts"},{flag:"--include-decisions"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--explain-ranking",aliases:["--explain_ranking"]}],uy=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],fy=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],py=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],my=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],_y=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],gy=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],hy=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],ru=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...hy],yy=ru,wy=[{flag:"--at"},{flag:"--text"},...hy],by=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-json"},{flag:"--remove"},{flag:"--remove-index",repeatable:!0},{flag:"--run"},{flag:"--match"},{flag:"--only-index"},{flag:"--only-last"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--acknowledge-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"},{flag:"--measure",list:!0},{flag:"--metric-below"},{flag:"--metric-diff"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],vy=[{flag:"--status"},{flag:"--limit"},{flag:"--offset"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"}],ky=[{flag:"--limit"}],Ey=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Sy=[{flag:"--dry-run"},{flag:"--scope"}],xy=[{flag:"--include-empty"},{flag:"--storage"},{flag:"--metadata-coverage"},{flag:"--field-utilization"},{flag:"--by-assignee"},{flag:"--by-tag"},{flag:"--by-priority"},{flag:"--tag-prefix"},{flag:"--analytics"}],Ty=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],Ay=[{flag:"--strict-directories"},{flag:"--require-merge-drivers"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--check-only"},{flag:"--check-telemetry"},{flag:"--no-refresh"},{flag:"--refresh-vectors"},{flag:"--verbose-stale-items"},{flag:"--verbose-author-events"},{flag:"--brief"},{flag:"--summary"},{flag:"--skip-vectors"},{flag:"--skip-integrity"},{flag:"--skip-drift"},{flag:"--full"}],Iy=[{flag:"--check-metadata"},{flag:"--metadata-profile"},{flag:"--check-resolution"},{flag:"--check-lifecycle"},{flag:"--check-stale-blockers"},{flag:"--dependency-cycle-severity"},{flag:"--parent-cycle-severity"},{flag:"--check-files"},{flag:"--scan-mode"},{flag:"--include-pm-internals"},{flag:"--verbose-file-lists"},{flag:"--verbose-diagnostics"},{flag:"--all-affected-ids"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--fix-hints"},{flag:"--auto-fix"},{flag:"--dry-run"},{flag:"--fix-scope"},{flag:"--prune-missing"},{flag:"--check-history-drift"},{flag:"--check-command-references"},{flag:"--check-storage-integrity"},{flag:"--counts"},{flag:"--full"}],ou=[{flag:"--definition",value_name:"json"},{flag:"--trigger",value_name:"value"},{flag:"--tree",value_name:"value"},{flag:"--gate",value_name:"id"},{flag:"--limit",value_name:"number"},{flag:"--dry-run"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--owner",value_name:"item-id"},{flag:"--apply",value_type:"boolean"},{flag:"--enforcement",value_name:"level"}],Cy=[{flag:"--assignee"},{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--allow-unresolved-deps"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-by"},{flag:"--blocked-reason"},{flag:"--unblock-note"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--actual-result"},{flag:"--affected-version"},{flag:"--fixed-version"}],Oy=[{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"}],Ry=[{short:"-p",flag:"--priority"},{flag:"--type"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{flag:"--remove-tags",aliases:["--remove_tags"]},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--add-ac",aliases:["--add_ac"]},{flag:"--remove-ac",aliases:["--remove_ac"]}],Xd=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{flag:"--id"},{short:"-d",flag:"--description"},{flag:"--type"},{flag:"--template"},{flag:"--create-mode"},{flag:"--create_mode"},{flag:"--schedule-preset"},{flag:"--schedule_preset"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},{flag:"--completed_at"},{short:"-p",flag:"--priority"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{short:"-b",flag:"--body"},{flag:"--body-file"},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--author"},{flag:"--message"},...Cy,...Oy,{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--fixed_version"},{flag:"--dep"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--reminder"},{flag:"--event"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--allow-duplicate",value_type:"boolean"}],Ny=[{flag:"--transaction-id",value_name:"value"},{flag:"--stdin-json"},{flag:"--dry-run"},{flag:"--create-compensation",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--author",value_name:"value"}],Dy=[{flag:"--id",value_name:"item-id"},{flag:"--transaction-id",value_name:"value",required:!0},{flag:"--reason",value_name:"value"},{flag:"--file",value_name:"value",repeatable:!0},{flag:"--doc",value_name:"value",repeatable:!0},{flag:"--test",value_name:"value",repeatable:!0},{flag:"--comment",value_name:"value",repeatable:!0},{flag:"--note",value_name:"value",repeatable:!0},{flag:"--learning",value_name:"value",repeatable:!0},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",value_name:"value"},{flag:"--actual-result",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--dry-run"},{flag:"--force"},{flag:"--author",value_name:"value"}],Py=[{flag:"--id",value_name:"item-id"},{flag:"--status",value_name:"open|in_progress"},{flag:"--message",value_name:"value"},{flag:"--force"},{flag:"--author",value_name:"value"}],Ly=[{flag:"--id",value_name:"item-id"},{flag:"--title",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--allow-duplicate",value_type:"boolean"}],My=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],$y=[{flag:"--id",value_name:"item-id"},{flag:"--stdin-json"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},{flag:"--body-file"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},...Ry,...Cy,{flag:"--fixed_version"},...Oy,{flag:"--author"},{flag:"--message"},{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--force"}],Fy=[{flag:"--filter-status",list:!0},{flag:"--filter-type",list:!0},{flag:"--filter-tag",list:!0},{flag:"--filter-priority",list:!0},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee",list:!0},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint",list:!0},{flag:"--filter-release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...zh,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...Ry,{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--repro_steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--expected_result"},{flag:"--expected"},{flag:"--actual-result"},{flag:"--actual_result"},{flag:"--actual"},{flag:"--affected-version"},{flag:"--affected_version"},{flag:"--fixed-version"},{flag:"--fixed_version"},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--allow-unresolved-deps"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Zd=[{flag:"--view"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--full-period"},{flag:"--full_period"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--status"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--include"},{flag:"--recurrence-lookahead-days"},{flag:"--recurrence-lookback-days"},{flag:"--occurrence-limit"},{flag:"--limit"},{flag:"--format"}],jy=[{flag:"--id"},{flag:"--op"},{flag:"--author"},{flag:"--from"},{flag:"--to"},{flag:"--limit"},{flag:"--unbounded"},{flag:"--compact"},{flag:"--raw"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--stream"}],Uy=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{flag:"--cursor-mode",value_name:"batch|row"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--follow"},{flag:"--interval-ms",value_type:"number"}],Qd=eu([{flag:"--for",value_name:"intent"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit",aliases:["--max-items"]},{flag:"--after"},{flag:"--format"},{flag:"--depth"},{flag:"--fields",list:!0},{flag:"--section"},{flag:"--activity-limit"},{flag:"--stale-threshold"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--no-extension-health"},{flag:"--no-tags"}],new Set(["--limit","--after","--format","--fields","--section","--activity-limit","--stale-threshold","--explain-ranking","--explain_ranking","--no-extension-health","--no-tags"])),zy=[{flag:"--id",value_name:"item-id"},{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--depth"},{flag:"--full",value_type:"boolean"},{flag:"--fields",list:!0},{flag:"--at"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--format"}],Hy=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],qy=[{flag:"--id",value_name:"item-id"},{flag:"--format"},{flag:"--max-depth"},{flag:"--collapse"},{flag:"--summary"},{flag:"--full"},{flag:"--node-limit"},{flag:"--edge-limit"},{flag:"--token-budget"},{flag:"--cursor"},{flag:"--direction"},{flag:"--kind",list:!0}],By=[{flag:"--kind",list:!0},{flag:"--max-depth"},{flag:"--limit"},{flag:"--after"},{flag:"--direction"},{flag:"--max-paths"},{flag:"--sample"},{flag:"--exempt-isolate",list:!0},{flag:"--exempt-isolate-type",list:!0},{flag:"--save-baseline"},{flag:"--rebuild"},{flag:"--clear"},{flag:"--summary"},{flag:"--full"}],Gy=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],jt=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],Vy=[],Wy=[{flag:"--for",value_name:"intent"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit"},{flag:"--blocked-limit"},{flag:"--blocked_limit"},{flag:"--ready-only"},{flag:"--ready_only"},{flag:"--format"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]}],Ky=eu([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--mode"},{flag:"--semantic"},{flag:"--hybrid"},{flag:"--match-mode"},{flag:"--min-score"},{flag:"--count"},{flag:"--semantic-weight"},{flag:"--include-linked"},{flag:"--title-exact"},{flag:"--phrase-exact"},{flag:"--highlight"},{flag:"--compact"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--format"},{flag:"--limit"},{flag:"--after"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--assignee",list:!0},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--parent"},...Uh],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Jy=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Yy=[{flag:"--eager-tags"}];var YD=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],XD=ta.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),ZD=ta.filter(e=>e.flag!=="--status");function ea(e){let t=new Map;for(let n of e)for(let r of[n.flag,...n.aliases??[]]){let o=t.get(r)??[];o.push(n),t.set(r,o)}return t}var QD=ea(tu),eP=ea(ou),tP=new Map([["assurance",eP],["plan",QD],["workspace",ea(Vy)],["workspace snapshot",ea(jt)]]);function Xy(e=Pr){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=tP.get(n);if(!o)throw new Error(`Positional action ${t} has no flag-contract index for ${n}.`);let i=r.map(s=>{let a=o.get(s)??[];if(a.length!==1)throw new Error(`Positional action ${t} accepted flag ${s} does not resolve to exactly one ${n} flag contract.`);return a[0]});return[t,i]})}var nP=Xy(),DJ=new Map([["list",ta],["list-all",ZD],...YD.map(e=>[e,XD]),["templates",Xd],["cal",Zd],["ctx",Qd],["test-runs-worker",Ey],["init",ny],["config",ry],["extension",nu],["package",Yd],["packages",Yd],["install",iy],["upgrade",sy],["create",Xd],["item mutate",Ny],["item complete",Dy],["item reopen",Py],["copy",Ly],["focus",My],["aggregate",Hh],["calendar",Zd],["context",Qd],["get",zy],["guide",Hy],["search",Ky],["next",Wy],["eval",Gy],["workspace",jt],["workspace position",Vy],["workspace snapshot",jt],["workspace snapshot create",jt],["workspace snapshot list",jt],["workspace snapshot inspect",jt],["workspace snapshot restore",jt],["workspace snapshot delete",jt],["history",Kh],["history-redact",Yh],["history-repair",Xh],["history-author-acknowledge",Zh],["history-compact",Qh],["merge",Jh],["schema",ey],["profile",ty],["plan",tu],["activity",jy],["events",Uy],["restore",uy],["update",$y],["update-many",Fy],["close",ay],["close-many",cy],["delete",fy],["append",ly],["comments",qh],["notes",Bh],["learnings",Gh],["files",Vh],["docs",Wh],["deps",qy],["graph",By],["test",by],["test-all",vy],["telemetry",ky],["health",Ay],["assurance",ou],...nP,["validate",Iy],["gc",Sy],["stats",xy],["duplicates",Ty],["contracts",Jy],["completion",Yy],["claim",dy],["release",py],["start-task",my],["pause-task",_y],["close-task",gy],["meet",ru],["event",yy],["remind",wy]]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19a97f60-3b6e-5653-a652-02aebaf5afdd")}catch{}})();var Zy={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Qy={if:{required:["field"]}};Reflect.set(Qy,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var ew={oneOf:[{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[Qy],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:Zy,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:Zy,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6968f481-8384-5e3b-8ac0-b0972d08eeb1")}catch{}})();var ei={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:ms,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},ifAbsent:{type:"boolean"},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},tw={assurance:{definition:ew,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},rP=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],iu={subcommand:{type:"string",enum:[...rP]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...ef]},mode:{type:"string",enum:[...Qu]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Ti]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...tf]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},su={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},ti={action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read linked commands).",examples:["schema","tracker","auto"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Return non-zero exit when health/validate/extension-doctor warnings are present."},failOnWarn:{description:"Alias for strictExit in health/validate/extension-doctor action payloads."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, or context outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Continuation cursor resuming a bounded listing or traversal after this previously returned id.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},nw={assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, or risk.",examples:["list","run","derive","promote","risk"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{name:{description:"Custom item type name (add-type/remove-type/show), custom status id (show-status/add-status/remove-status), or custom field key (add-field/remove-field/show-field). Required for those subcommands.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b81a68c1-565d-56f6-a0eb-35d2c737bdb7")}catch{}})();var iP=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],sP=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],aP=new Set(["action","cwd","options",...Object.keys(ei).filter(e=>e!=="severity")]);var cP={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},cw=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],WJ=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(rn.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function et(e){return Jd(e)}var lP=et([...zd.map(e=>e.param),...Qs.map(e=>e.param),"assignee","closeReason","completedAt"]),lw=et([...Hd.map(e=>e.param),...Qs.map(e=>e.param),"force"]),dP=et([...Bd.map(e=>e.param),...lw.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),uP=et([...Gd.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),rw=et([...Wd.map(e=>e.param),"past","section"]),fP=et([...Vd.map(e=>e.param),"stream"]),au=et([...Fd.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),Lr=au.filter(e=>e!=="all"&&e!=="status"),pP=au.filter(e=>e!=="status"),hn=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],mP=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],_P=et([...jd.map(e=>e.param),"count","completion","includeUnparented"]),gP=et(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Ud.map(e=>e.param)]),ow=et(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),qe=["author","message","force"],dw=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],ni=["author","assignee","message","force"],hP=["target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function iw(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:hP}}}var sw={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},aw={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},na={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...iw("extension"),...iw("package"),"package-upgrade":aw,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:aw,create:{required:["title","description","type","status","priority","message"],optional:lP},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:au,mutuallyExclusiveWhen:hn},"list-all":{optional:pP,mutuallyExclusiveWhen:hn},"list-draft":{optional:Lr,mutuallyExclusiveWhen:hn},"list-open":{optional:Lr,mutuallyExclusiveWhen:hn},"list-in-progress":{optional:Lr,mutuallyExclusiveWhen:hn},"list-blocked":{optional:Lr,mutuallyExclusiveWhen:hn},"list-closed":{optional:Lr,mutuallyExclusiveWhen:hn},"list-canceled":{optional:Lr,mutuallyExclusiveWhen:hn},aggregate:{optional:_P},guide:{optional:["list","format","depth"]},context:{optional:rw},ctx:{optional:rw},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:gP,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:sw,event:sw,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...ow,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...qe],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...qe],oneOfRequired:[["id"],["all"]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...qe]},schema:{required:["subcommand"],optional:["name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...cw,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...qe]},activity:{optional:fP},restore:{required:["id","target"],optional:qe},update:{required:["id"],optional:lw,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:dP,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...dw,...qe]},"close-many":{optional:uP},delete:{required:["id"],optional:["dryRun",...qe]},append:{required:["id","body"],optional:qe},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...qe],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...qe],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...qe],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...qe],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...qe],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["add","addJson","remove","removeIndex","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...qe],mutuallyExclusive:[["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:mP},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...ow,...ni],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:ni},"start-task":{required:["id"],optional:ni},"pause-task":{required:["id"],optional:ni},"close-task":{required:["id"],optional:["text","validateClose",...ni]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},yP=Object.freeze(Object.fromEntries(rn.map(e=>[e,na[e]])));function uw(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function wP(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=ti[e];return{...n,description:r?.description??uw(e),...r?.examples?{examples:r.examples}:{}}}function bP(e,t){if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(su,t))return su[t];let n=nw[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:ti[t]}function vP(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=bP(e,t);return{...r,description:o?.description??uw(t),...o?.examples?{examples:o.examples}:{}}}function kP(e,t){let n=tw[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(iu,t)?iu[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:ei[t]}function EP(e,t){let n={action:{const:e,description:ti.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=kP(e,r);o&&(n[r]=vP(e,r,o))}return n}function SP(e,t){let n=t.flat();return t.map(r=>{let o=n.filter(i=>!r.includes(i));return{required:[...r],...o.length>0?{not:{anyOf:o.map(i=>({required:[i]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function xP(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:{properties:{[n.property]:{const:n.value}},required:[n.property]},then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:{required:[n.property]},then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:et(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function fw(e){if(!Object.prototype.hasOwnProperty.call(na,e))return;let t=na[e],n=cP[e]??[];return et(["action",...iP,...go(e)!==void 0?sP:[],...n,...t.required??[],...t.optional??[]])}function TP(e){let t=na[e],n=et(t.required??[]),r=fw(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:EP(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=SP(e,t.oneOfRequired));let i=xP(t);return i.length>0&&(o.allOf=i),o}function pw(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,o)=>n()[o],has:(r,o)=>o in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,o)=>{let i=Reflect.getOwnPropertyDescriptor(n(),o);return i&&(i.configurable=!0),i}})}var cu="4.10.1",mw=cu.split(".")[0],_w="1.4.0",AP=pw(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${mw}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":cu,type:"object",oneOf:rn.map(e=>TP(e))}));function IP(e,t){let n=wP(e,t);if(typeof n.type=="string")return n;let o=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(o){let{anyOf:a,...c}=n;return{...o,...c}}let{anyOf:i,...s}=n;return{...s,type:"string"}}function CP(){let e={action:{type:"string",description:ti.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(ei).sort())e[t]=IP(t,ei[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":_w,type:"object",additionalProperties:!1,required:["action"],properties:e}}var OP=pw(CP);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4e5eed5-94c2-536a-8685-e20b735de480")}catch{}})();var QJ=new Set([...Vm,...Wm]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="167b98d4-a5b5-581d-ac0a-17e8e3bfc490")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d42d5fb1-eebc-5549-ae88-dc923d9d3696")}catch{}})();var UP=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),r7=new Set([...UP].filter(e=>e!=="file"));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var zP="2026-07-15T06:22:12.276Z",HP=Date.parse(zP),qP=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],hw=e=>typeof e=="string"?e:"",BP=e=>{let t=e??{},n=hw(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(hw(t.ts))>=HP);return qP[r][o]};function GP(e,t,n=20,r=new Set,o=!1){let i=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let m;try{m=JSON.parse(p)}catch{continue}l+=1;let g=BP(m);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[g]+=1,o&&g==="actionable_unknown"&&s.push({item_id:e,line:f+1}),i.length<c&&i.push({item_id:e,line:f+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:s}}function VP(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let s of i.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var ra=async(e,t=20,n=!1)=>{let r=du.join(e,"history"),o;try{o=(await lu.readdir(r)).filter(b=>b.endsWith(".jsonl")).sort((b,v)=>b.localeCompare(v))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,m="_workspace.jsonl",g=new Set;if(o.includes(m))try{g=VP(await lu.readFile(du.join(r,m),"utf8"))}catch{g=new Set}for(let b of o){let v;try{v=await lu.readFile(du.join(r,b),"utf8")}catch{continue}let A=b.slice(0,-6),I=GP(A,v,t-s.length,g,n);c+=1,l+=I.checked_events,d+=I.unknown_event_count,u+=I.legacy_unknown_event_count,f+=I.actionable_unknown_event_count,p+=I.acknowledged_actionable_event_count,I.unknown_event_count>0&&i.add(A),s.push(...I.samples),n&&a.push(...I.actionable_events)}let y=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...i].sort((b,v)=>b.localeCompare(v)),samples:s,samples_truncated:y>s.length,...n?{actionable_events:a}:{}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c514907-377f-59f9-bfdd-a184abf7ffb7")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ec456832-5120-5171-93fd-861ea4125acb")}catch{}})();var v7=new Set(rr),WP=new Set(Gr.map(e=>we(e.id)).filter(e=>e.length>0));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b5a573e-1e36-58b9-b93b-4a4088f71e9a")}catch{}})();var A7=new Set(Wt),I7=new Set(or),C7=new Set([...Le.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="13c02696-29a7-598e-888a-3502fd88bfbe")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6ed4a26f-2ae2-556a-87db-56844108757f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60738c1f-3b44-5f8a-82c9-99d2b2de1e51")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="264088a5-09d1-52ed-8b12-af00392e1a5f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af718efb-d1cf-5adc-9518-c858627e1b54")}catch{}})();function uu(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}import rL from"node:fs/promises";import oL from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="159d7bbd-1d2a-503d-b3ce-f32dcc6f6547")}catch{}})();var iL=".managed-extensions.json",fu=1;function pu(e){return oL.join(e,iL)}function sL(){return{version:fu,updated_at:F(),entries:[]}}function ww(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.name.localeCompare(n.name);return o!==0?o:t.directory.localeCompare(n.directory)})}function tt(e){return typeof e=="string"?e:void 0}function aL(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function cL(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:tt(t.name),package:tt(t.package),version:tt(t.version),repository:tt(t.repository),owner:tt(t.owner),repo:tt(t.repo),ref:tt(t.ref),subpath:tt(t.subpath),commit:tt(t.commit)}}function lL(e){if(typeof e!="object"||e===null)return null;let t=e;if(!aL(t))return null;let n=cL(t.source);if(!n)return null;let r=io(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:uu(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:tt(t.last_update_check_at),last_update_remote_commit:tt(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:tt(t.update_error)}}function dL(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==fu||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let o=lL(r);o&&n.push(o)}return{version:fu,updated_at:tt(t.updated_at)??F(),entries:ww(n)}}async function oi(e){let t=pu(e),n=sL();try{let r=await rL.readFile(t,"utf8"),o=JSON.parse(r),i=dL(o);if(!i)throw new w(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE);return{path:t,state:i,warnings:[]}}catch(r){if(r instanceof w)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&j(r))return{path:t,state:n,warnings:[]};throw new w(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,h.GENERIC_FAILURE)}}import{execFile as mL}from"node:child_process";import{promisify as _L}from"node:util";import FZ from"npm-package-arg";import{extract as UZ,list as zZ}from"tar";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6fc24a7c-a359-51fd-a432-4c8037d10e9e")}catch{}})();var bZ=Object.freeze({extensions:Object.freeze([".agents/pm/extensions","extensions",".custom/pm-extensions",".custom/pm-extension"]),docs:Object.freeze(["docs","documentation"]),examples:Object.freeze(["examples","docs/examples"]),assets:Object.freeze(["assets",".agents/pm/assets"]),prompts:Object.freeze(["prompts",".agents/pm/prompts"])});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="259656b0-09b7-52c5-8f54-52ac29eec607")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05f56edb-c08d-570c-b8b5-641fc694331e")}catch{}})();var JZ=_L(mL);var YZ={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5321d574-4de4-5f94-99db-0c49639673fc")}catch{}})();var rQ=new Set([...hr.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(nl).map(e=>e.toLowerCase()),"scaffold"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48c3e62a-8085-5215-a692-4c03792022ce")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="536ed530-7726-50ab-bb2d-ace030818f1d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54ce5bae-db04-5c19-81df-093802bf41c7")}catch{}})();var vw=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function yL(e){return vw.has(vL(e))}function bw(e){return e==="project"||e==="global"}function wL(e){let t=e.split(":"),n=t[0];if(!n||!vw.has(n))return null;let r=t.at(-4),o=t.at(-3)?.trim(),i=t.at(-2),s=t.at(-1)?.trim();return!bw(r)||!bw(i)||!o||!s?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:o},displaced:{layer:i,name:s}}}function bL(e){let t=new Set;for(let n of e){let r=wL(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function kw(e,t){let n=e.filter(yL);if(n.length===0)return null;let r=bL(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function vL(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function mu(e){let t=new Set,n=[];for(let r of e){let o=(()=>{let i=uc(r);return i?[i]:fc(r)})();for(let i of o){let s=`${i.layer}:${i.name}:${i.capability}`;t.has(s)||(t.add(s),n.push(i))}}return n}function _u(){return{version:_i.version,capabilities:[..._i.capabilities],legacy_aliases:{..._i.legacy_aliases}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="263602a2-c000-5df7-80d2-6f095985496f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b17dfc10-9e07-5912-b294-c5663133f192")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5a4cea9-ac5d-5bda-9f7c-6cf8cf9e9998")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17145dd7-3938-5f20-b5b5-49f8d38d3d8d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb857a5-045d-57a7-91d2-b761225fe53a")}catch{}})();import kL from"node:fs/promises";import EL from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="56290db9-933c-590d-8b9f-df62ff45e515")}catch{}})();function SL(e){return EL.join(e,"extension-migrations.json")}function xL(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function TL(e,t){return`${e.layer}:${e.name}:${t}`}async function AL(e){let t=SL(e);if(!await U(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await kL.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function Ew(e,t){let n=await AL(e),r=new Map(n.entries.map(o=>[o.key,o]));return t.forEach((o,i)=>{let s=xL(o,i),a=r.get(TL(o,s));a&&(o.definition.status=a.status,a.status==="failed"?o.definition.reason=a.error:(delete o.definition.reason,delete o.definition.error,delete o.definition.message))}),n}import IL from"node:fs/promises";import CL from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5755dee7-d2df-5ced-8a94-aeb51762edb7")}catch{}})();function OL(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function RL(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function Sw(e){let t=CL.join(e,"manifest.json"),n;try{n=await IL.readFile(t,"utf8")}catch(a){if(ut(a))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw a}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let o=r,i=wc(o),s=OL(o);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:i.findings,warnings:i.findings.map(a=>RL(s,a)),remediation:i.findings.map(a=>a.message)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="39bc7f14-2d32-5b58-97ab-647f9f238273")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98b47a2f-d48a-5c90-8b88-3f33bdd1c826")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d5ed026-8d61-5083-956c-9281caa0168b")}catch{}})();var LL=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],bte=LL.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", ");var vte=es();import gu from"node:fs/promises";import hu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb3bf7ee-808f-5ff6-af84-edb034760c54")}catch{}})();var ML=8388608,$L=new Set(["resolved","failed"]),FL=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yu(e){return FL.find(t=>t.matches(e))?.kind}function xw(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=It(i.agent_provenance)?i.agent_provenance:void 0;if(s===void 0||!an(i).ok)return i;let a={},c=!1;for(let[d,u]of Object.entries(s)){let f=It(u)?yu(u.value):void 0;if(f===void 0){a[d]=u;continue}c=!0,r+=1;let p=i.agent_harness??"unknown",m=`${p}\0${d}\0${f}`,g=t.get(m)??{harness:p,dimension:d,kind:f,count:0};g.count+=1,t.set(m,g)}if(!c)return i;n+=1;let l={...i};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,vr(i,l,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension)||i.kind.localeCompare(s.kind))}}}async function Tw(e){let t=[];for(let n of await Aw(e))try{let r=await gu.readFile(hu.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
115
|
+
`)){if(o.trim().length===0)continue;let i=Iw(o);if(i===null||!It(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>It(a)&&yu(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Aw(e){try{return(await gu.readdir(hu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function jL(e,t,n){let r;try{r=await gu.open(hu.join(e,"history",t),"r");let o=(await r.stat()).size,i=Math.min(o,Math.max(0,n)),s=Buffer.alloc(i),{bytesRead:a}=await r.read(s,0,i,0),c=s.subarray(0,a).toString("utf8"),l=a>=o,d=c.lastIndexOf(`
|
|
116
|
+
`),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:a,complete:l}}catch{return null}finally{await r?.close()}}function Iw(e){try{let t=JSON.parse(e);return It(t)?t:null}catch{return null}}function UL(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let o=It(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(o).forEach(([s,a])=>{if(!It(a))return;let c=yu(a.value);if(!c)return;let l=`${r}\0${s}\0${c}`,d=n.get(l)??{harness:r,dimension:s,kind:c,count:0};d.count+=1,n.set(l,d)}),!It(e.context))return;let i=e.context.agent_provenance_outcomes;It(i)&&Object.entries(i).forEach(([s,a])=>{if(!It(a)||typeof a.resolver!="string"||!$L.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,l=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};l.attempts+=1,a.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function zL(e,t,n,r,o){let i=o;for(let s of e.split(`
|
|
117
|
+
`)){if(s.trim().length===0)continue;if(i>=r)return{eventsRead:i,truncated:!0};i+=1;let a=Iw(s);a&&UL(a,t,n)}return{eventsRead:i,truncated:!1}}async function Cw(e,t=1e4){let n=new Map,r=new Map,o=0,i=0,s=!1;for(let l of await Aw(e)){let d=await jL(e,l,Math.max(0,ML-i));if(d===null)continue;i+=d.bytesRead;let u=zL(d.content,n,r,t,o);if(o=u.eventsRead,u.truncated){s=!0;break}if(!d.complete){s=!0;break}}let a=[...n.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.resolver.localeCompare(d.resolver)),c=[...r.values()].sort((l,d)=>l.harness.localeCompare(d.harness)||l.dimension.localeCompare(d.dimension)||l.kind.localeCompare(d.kind));return{outcomes:a,invalid_values:c,warnings:s?[]:[...a.filter(l=>l.attempts>0&&l.successes===0).map(l=>`provenance_resolver_zero_success:${l.harness}:${l.dimension}:${l.resolver}:${String(l.attempts)}`),...c.map(l=>`provenance_value_domain_invalid:${l.harness}:${l.dimension}:${l.kind}:${String(l.count)}`)],events_read:o,truncated:s}}import{execFile as HL}from"node:child_process";import{realpath as qL}from"node:fs/promises";import Ow from"node:path";import{promisify as BL}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var GL=BL(HL),VL=32*1024*1024,WL=1e4,KL=["search/eval-queries.json"];function wu(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function JL(e){return`'${e.replaceAll("'","'\\''")}'`}async function YL(e,t=qL){return t(e).catch(()=>Ow.resolve(e))}async function oa(e){let t=await Et(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await YL(e),r=wu(Ow.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let o=og.map(i=>`${r}/${wu(i)}`);try{let{stdout:i}=await GL("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:VL,windowsHide:!0,timeout:WL}),s=new Set(KL.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(wu(l))))].sort((l,d)=>l.localeCompare(d)),c=o.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>JL(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import{createHash as XL}from"node:crypto";import ia from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e73338f-221a-580f-85a8-6f2a488fb89d")}catch{}})();var vu="2026-08-09T16:15:18.000Z",Nw=Symbol("pre-durable-disposition-eligible");function zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bu(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function Rw(e){return zt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function Dw(e,t){if(typeof e!="string")return!1;let n=ia.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ia.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ia.posix.basename(n)===`${t}.toon`||ia.posix.basename(n)===`${t}.md`)}function ZL(e,t){return typeof e.receipt_id=="string"&&Bn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Dw(e.item_path,t)}function Pw(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,o=e.decisions,i=Array.isArray(o)?new Set(o.flatMap(s=>Rw(s)?[s.field]:[])):new Set;return bu(t)&&bu(n)&&bu(r)&&Array.isArray(o)&&o.length>0&&o.length<=256&&Object.keys(o).length===o.length&&o.every(Rw)&&i.size===o.length&&t.length===i.size&&t.every(s=>i.has(s))}function QL(e,t){return ZL(e,t)&&Pw(e)}function eM(e,t){return typeof e.receipt_id=="string"&&Bn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&Dw(e.item_path,t)&&Pw(e)}function ku(e){return e[Nw]===!0}function sa(e,t){if(!zt(e)||!zt(e.context))return[];let n=e.context.merge;return!zt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!zt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:QL(r,t),[Nw]:eM(r,t),...typeof e.ts=="string"&&Ot(e.ts)?{eventTimestamp:e.ts}:{}}])}function Lw(e,t,n){if(!zt(e)||e.op!=="merge_reconcile")return[];if(!zt(e.context)||!zt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(o=>!zt(o)||typeof o.receipt_id!="string"||!Bn(o.receipt_id)||typeof o.original_history_line!="number"||!Number.isSafeInteger(o.original_history_line)||o.original_history_line<1||typeof o.original_event_ts!="string"||!Ot(o.original_event_ts)||o.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:o.receipt_id,originalHistoryLine:o.original_history_line,originalEventTimestamp:o.original_event_ts,auditHistoryLine:n,reason:o.reason}])}function Mw(e,t,n=[]){let r=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;r.set(a,Math.max(r.get(a)??0,s.auditHistoryLine))}let o=s=>ku(s)&&s.eventTimestamp!==void 0&&me(s.eventTimestamp,vu)<0&&(r.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!o(s)).map(s=>({item_id:s.itemId,history_line:s.line,...Bn(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:XL("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(o).length}}import{realpath as zw}from"node:fs/promises";import iM from"node:path";import Hw from"fast-json-patch";import tM from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function nM(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=fn(e.settings);if(n.ownership_enforcement==="strict")throw new w(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,h.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function rM(e){let t=await Z(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new w(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);let n=await Ze(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await He(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new w(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function $w(e){let t=e.writeHistoryRaw??H;try{await t(e.historyPath,e.nextHistoryRaw),await on(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await tM.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await on(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function Eu(e){let t=[...nM({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await ke(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await rM({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47c087c2-124a-58b7-a5c9-09403235f4a2")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd1e86b0-6696-5fba-8dd4-b9636bf3ee60")}catch{}})();async function Fw(e,t,n,r){let o=await Ze(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:gt(e,o.id),located:o};let i=_n(t,n.id_prefix),s=Cr(t),a=i===s?[i]:[i,s];for(let c of a){let l=gt(e,c);if(await U(l))return{id:c,historyPath:l,located:null}}throw new w(`Item ${t} not found`,h.NOT_FOUND)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb0b0e36-3135-5fc4-a0ae-f4e5b974e57f")}catch{}})();function jw(e,t){return t==="body"?e.body:e.metadata[t]}function Su(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(o=>{let i=t.findIndex((s,a)=>!r.has(a)&&Su(o,s));return i<0?!1:(r.add(i),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,o])=>Object.hasOwn(n,r)&&Su(o,n[r]))}function Uw(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let i=e[o],s=new Set;for(let c of bo(i.patch))s.add(Yo(c.path)),c.from&&s.add(Yo(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:o+1,ts:i.ts,author:i.author,op:i.op,fields:a.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function sM(e,t,n){let r=Hw.compare(t,n);if(r.length===0)return;let o=new Set;for(let m of r)o.add(Yo(m.path));let i=new Set([...o].filter(m=>Su(jw(t,m),jw(n,m)))),s=new Set([...o].filter(m=>!i.has(m))),a=Uw(e,s),c=Uw(e,i),l=[...o].sort((m,g)=>m.localeCompare(g)),d=[...s].sort((m,g)=>m.localeCompare(g)),u=[...i].sort((m,g)=>m.localeCompare(g)),f=[...new Set(a.map(m=>m.author))].sort((m,g)=>m.localeCompare(g)),p=[...new Set(c.map(m=>m.author))].sort((m,g)=>m.localeCompare(g));return{reconciled_field_count:o.size,reconciled_fields:l,reverted_field_count:s.size,reverted_fields:d,discarded_events:a,discarded_authors:f,preserved_field_count:i.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function aM(e){try{return await zw(e)}catch{return null}}async function cM(e){if(await aM(iM.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let o=Object.keys(r).sort();if(n.length!==o.length||n.some((a,c)=>a!==o[c]))return null;let i=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:i[a];return[vt(c),ye(N(Ne(c)))].includes(r[a])})?{receipt:e.receipt,declaredFields:n}:null}async function lM(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await zw(e.itemPath),r=[];for(let s of t){let a=await cM({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let o=new Set(r.flatMap(({declaredFields:s})=>s)),i=e.reconciliation?.reconciled_fields;return r.length>0&&(i===void 0||i.length>0&&i.every(s=>o.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function dM(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await ft(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],o=e.options.mergeReceiptProof?await lM({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(o&&!o.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new w(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${o.reason}).`,h.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=o?.trusted?r.filter(s=>o.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:o,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(Ft)}}:e.options.auditContext}}async function uM(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await He(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=_l(i.document),a=n[n.length-1].after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:cn(s,r).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function fM(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function pM(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=cn(e.finalReplay,e.itemHashVersion),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,i=r.indexOf(o),s=cn(n,e.itemHashVersion),a={ts:F(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Hw.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[i],after_hash:s[i],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(br({...a,event_class:Fn(a)})),{rewrittenEntries:t,auditEntryAdded:!0}}function mM(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function _M(e){return Eu({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>$w({historyPath:e.historyPath,nextHistoryRaw:ln(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>je({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Mr(e,t,n){let r=te(process.cwd(),n.path);await Ie(r);let o=await oe(r),i=de(o,K()),s=await Fw(r,e,o,i.type_to_folder);if(!await U(s.historyPath))throw new w(`No history stream exists for ${s.id}.`,h.NOT_FOUND);let a=await Z(s.historyPath),c=await Mt(s.historyPath,s.id);if(c.length===0)throw new w(`No history entries exist for ${s.id}; nothing to repair.`,h.USAGE);let l=zn(c),d=Un(c),u=t.normalizeProvenance?xw(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=gl(u.entries),p=new Set(u.entries.map(De=>De.item_hash_version).filter(De=>De!==void 0)),m=vo(u.entries,f),g=await uM(s,o,c,f),y=m.finalDocument,b=cn(y,f),v=!1;if(g.currentItemReplay!==null){let De=cn(g.currentItemReplay,f);v=!b.some((Pe,nt)=>Pe===De[nt])}let A=v&&g.currentItemReplay?sM(m.entries,y,g.currentItemReplay):void 0,{mergeReceiptProof:I,effectiveAuditContext:x}=await dM({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:g,reconciliation:A}),P=[m.entriesRehashed>0,m.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),S=Ye(t.author,o.author_default),E=!!t.dryRun,$=fM({message:t.message,entriesRehashed:m.entriesRehashed,entriesPatchRepaired:m.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:Q,auditEntryAdded:M}=pM({reanchorEntries:m.entries,changed:P,reconcileNeeded:v,currentItemReplay:g.currentItemReplay,finalReplay:y,author:S,message:$,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...x,provenance_normalization:u.receipt}:x,itemHashVersion:f,explicitItemHashVersion:m.explicitItemHashVersion}),R=zn(Q);if(!R.ok)throw new w(`history-repair produced an invalid rewritten chain (${R.errors.join(", ")}).`,h.GENERIC_FAILURE);let ee=mM(P,m.skippedOps,A);return P&&!E&&ee.push(...await _M({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:S,force:t.force,loadedItem:g.loadedItem,historyPath:s.historyPath,rewrittenEntries:Q})),{id:s.id,dry_run:E,changed:P,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!l.ok,entries_rehashed:m.entriesRehashed,entries_patch_repaired:m.entriesPatchRepaired,converted_replace_to_add:m.convertedReplaceToAdd,skipped_ops:m.skippedOps,reconciled_with_item:v,audit_entry_added:M,verify_ok:R.ok,verify_errors:R.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:g.currentItemPath!==null,path:g.currentItemPath,matched_chain_before:g.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...A?{reconciliation:A}:{},...I?{merge_receipt_proof:I}:{},warnings:[...new Set(ee)].sort((De,Pe)=>De.localeCompare(Pe)),generated_at:F()}}async function qw(e,t){let n=te(process.cwd(),t.path);await Ie(n);let r=await oe(n),o=de(r,K()),i=[],s=await Xn(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await Jn(n,s),c=e.normalizeProvenance?await Tw(n):[],l=[...new Set([...a.driftedItems,...c])].sort((p,m)=>p.localeCompare(m)),d=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let p of l)try{let m=await Mr(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),g=m.changed?"repaired":"skipped_clean";f[g]+=1,u.push(...m.warnings.map(y=>`${p}:${y}`)),d.push({id:p,outcome:g,entries_rehashed:m.history.entries_rehashed,entries_patch_repaired:m.history.entries_patch_repaired,reconciled_with_item:m.history.reconciled_with_item,...m.reconciliation?{reconciliation:m.reconciliation}:{},...m.merge_receipt_proof?{merge_receipt_proof:m.merge_receipt_proof}:{},warnings:m.warnings})}catch(m){f.failed+=1,d.push({id:p,outcome:"failed",error:m instanceof Error?m.message:String(m)})}return e.dryRun||await ll(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:f,warnings:[...new Set([...i,...u])].sort((p,m)=>p.localeCompare(m)),generated_at:F()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="971d929f-12be-5648-93c9-8a9878b40dde")}catch{}})();function aa(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function ii(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3f3beb2-1d60-52fe-88ce-1ab3cb9dba0d")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d49d73c9-f988-5c3c-a22d-0580ee5526f6")}catch{}})();function Ht(){let e=Cn();for(let t of K()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="924f7718-0527-5967-8ab0-53e8228bd665")}catch{}})();function la(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function ca(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function gM(e,t){let n=new Set,r=[];for(let o of[...e].sort()){if(n.has(o))continue;n.add(o);let i=[{nodeId:o,children:[...t.get(o)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),i.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),i.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function hM(e,t){let n=[...e].sort(),r=gM(n,t),o=new Set,i=yM(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=wM(a,i,o);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function yM(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,o]of t)for(let i of o)n.get(i)?.add(r);return n}function wM(e,t,n){let r=[],o=[e];for(n.add(e);o.length>0;){let i=o.pop();r.push(i);for(let s of[...t.get(i)].sort())n.has(s)||(n.add(s),o.push(s))}return r.sort()}function bM(e){let t=new Map;for(let n of e){let r=la(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function vM(e,t,n){let r=la(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function kM(e,t,n,r){let o=la(t?.id),i=r.resolve(t?.kind);if(!o||!n.has(o)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:o,child_id:s?o:e,source:"dependency",kind:i.kind,holder_id:e,target_id:o,child_cardinality:s?i.incoming:i.outgoing}}function EM(e,t){let n=new Map;for(let[r,o]of e){let i=vM(r,o,e);i&&n.set(ca(i),i);for(let s of o.dependencies??[]){let a=kM(r,s,e,t);a&&n.set(ca(a),a)}}return[...n.values()].sort((r,o)=>ca(r).localeCompare(ca(o)))}function SM(e,t,n){let r=new Set(e.filter(o=>o.child_cardinality==="one").map(o=>o.child_id));return[...t].filter(([o,i])=>i.length>1&&r.has(o)).map(([o,i])=>({child_id:o,parent_ids:[...i],legacy_terminal:n.has(o)&&i.every(s=>n.has(s))})).sort((o,i)=>o.child_id.localeCompare(i.child_id))}function xM(e,t,n){let r=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=r.get(i.child_id)??new Set;s.add(i.parent_id),r.set(i.child_id,s)}let o=[];for(let[i,s]of e){let a=la(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(i)??[]].filter(l=>l!==a).sort();c.length!==0&&o.push({child_id:i,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(i)&&n.has(a)&&c.every(l=>n.has(l))})}return o.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function si(e,t=r=>r==="closed"||r==="canceled",n=Ht()){let r=bM(e),o=EM(r,n),i=TM(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=hM([...r.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:o,cycles:a,cardinality_violations:SM(o,i.parents_by_child,s),divergences:xM(r,o,s)}}function TM(e){let t=new Map,n=new Map;for(let r of e){let o=t.get(r.child_id)??new Set;o.add(r.parent_id),t.set(r.child_id,o);let i=n.get(r.parent_id)??new Set;i.add(r.child_id),n.set(r.parent_id,i)}return{parents_by_child:new Map([...t].map(([r,o])=>[r,[...o].sort()])),children_by_parent:new Map([...n].map(([r,o])=>[r,[...o].sort()]))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e04a91fa-4625-50fd-9bfd-c712126baf0d")}catch{}})();function Bw(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function AM(e,t,n=!0){let r=Bw(e);return n&&(ii(t)||r!==void 0&&aa(r))}function Gw(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),o=new Map,i=(c,l,d,u,f)=>{let p=Bw(l);if(!p||r.has(p.toLowerCase())||AM(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};o.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;ii(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...o.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function da(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),o=new Set(r),i=t.filter(s=>{let a=sr(s.status,e);return a!==void 0&&o.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:i.length,affected_item_ids:i.slice(0,n),affected_item_ids_truncated:i.length>n}}function ua(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9f0077a4-4f0a-540f-9951-2e8a640629c9")}catch{}})();var IM=new Set(Cd),Jw=25,$r=8,Qn=100,CM=Be.join("runtime","telemetry","events.jsonl"),OM=Be.join("runtime","telemetry","state.json"),RM=2500,NM=500,Yw=hh-3,DM=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Xw(e,t=!1){return e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Zw(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function ci(e){return e.trim().toLowerCase()}function Vw(e,t){let n=ci(e),r=ci(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Qw(e){try{return(await Bt.stat(e)).isDirectory()}catch{return!1}}async function PM(e){let t=(await Bt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>Bt.readdir(Be.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(o=>o.isFile()).filter(o=>Nt.some(i=>o.name.endsWith(i))).map(o=>Be.parse(o.name).name)))}async function LM(e,t,n,r){let o=await Ue({path:e,scope:"project"}),i=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!i)return{warnings:o,overThreshold:!1,classification:"live"};let s;try{s=await Bt.readFile(e,"utf8")}catch{return{warnings:o,overThreshold:!1,classification:"unreadable"}}let a="live";if(i){let l=s.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{a=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{a="orphaned"}}let c=n.enabled?s.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:o,overThreshold:n.enabled&&c>n.max_entries,classification:a}}async function MM(e,t,n){let r=Be.join(e,"history");if(!await Qw(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let o=(await Bt.readdir(r)).filter(u=>u.endsWith(".jsonl")).sort((u,f)=>u.localeCompare(f)),s=t.enabled?t.max_entries:null,a=[],c=[],l=[],d=[];for(let u of o){let f=Be.join(r,u),p=u.slice(0,-6),m=await LM(f,p,t,n);a.push(...m.warnings),m.classification==="tombstone"&&l.push(p),m.classification==="orphaned"&&d.push(p),m.overThreshold&&c.push(p)}return{count:o.length,warnings:[...a,...c.map(u=>`history_stream_over_compact_threshold:${u}`),...d.map(u=>`history_orphaned_stream:${u}`)],over_threshold:c,max_entries:s,tombstones:l,orphaned:d}}function Iu(e,t){return Be.relative(e,t).replaceAll("\\","/")}async function $M(e,t){let n=[...new Set(Object.values(t))].sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=Be.join(e,o),s=[];try{s=await Bt.readdir(i)}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&j(a))continue;continue}for(let a of s)Nt.some(c=>a.toLowerCase().endsWith(c))&&r.push(Be.join(i,a))}return r.sort((o,i)=>Iu(e,o).localeCompare(Iu(e,i))),r}function FM(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function jM(e,t,n){let r=await $M(e,t),o=[],i=[],s=[],a=[],c=pt(K());for(let l of r){let d=Iu(e,l),u;try{u=await Bt.readFile(l,"utf8")}catch{o.push(d);continue}let f=Me(u);if(f){i.push({path:d,...f});continue}try{let p=$e(u,{format:pr(l),schema:n,extensionFieldNames:c});a.push({ref:d,version:Fi(p.metadata)})}catch{s.push(d)}}return{paths:r,unreadable:o,conflictMarkers:i,parseFailures:s,formatVersions:a}}async function UM(e){let t=Be.join(e,"history"),n=[],r=[],o=[],i=[],s=[],a=[];try{a=(await Bt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,l)=>c.localeCompare(l))}catch(c){FM(c)&&n.push("history")}for(let c of a){let l=c.slice(0,-6),d;try{d=await Bt.readFile(Be.join(t,c),"utf8")}catch{n.push(l);continue}let u=Me(d);if(u){r.push({id:l,...u});continue}d.split(/\r?\n/).forEach((f,p)=>{if(f.trim())try{let m=JSON.parse(f);i.push(...sa(m,l).map(g=>({itemId:l,line:p+1,...g}))),s.push(...Lw(m,l,p+1))}catch{o.push({id:l,line:p+1})}})}return{files:a,unreadable:n,conflictMarkers:r,invalidJson:o,mergeReceiptReferences:i,mergeReceiptDispositions:s}}function zM(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}function HM(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}async function qM(e,t,n,r,o){let i=await jM(e,t,n),s=await UM(e),a=ji(i.formatVersions),c=Rt(n),l=si(o,E=>$a(E,c),Ht()),d=await oa(e),u=await Et(e),f=u===null?null:await Oo(u),p=await ft(u??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),m=new Set(p.receipts.map(E=>E.id)),g=Mw(s.mergeReceiptReferences,m,s.mergeReceiptDispositions),y=g.missing,b=p.receipts.filter(E=>E.state==="pending"),{pendingDecisions:v,lossless:A}=Es(b),I=f?.status==="missing"&&f.missing_keys.length===5&&f.drifted_keys.length===0,x=[...i.unreadable.map(E=>`integrity_item_unreadable:${E}`),...i.conflictMarkers.map(E=>`integrity_item_conflict_marker:${E.path}:L${E.line}`),...i.parseFailures.map(E=>`integrity_item_parse_failed:${E}`),...s.unreadable.map(E=>`integrity_history_unreadable:${E}`),...s.conflictMarkers.map(E=>`integrity_history_conflict_marker:${E.id}:L${E.line}`),...s.invalidJson.map(E=>`integrity_history_invalid_json:${E.id}:L${E.line}`),...a.outdated.map(E=>`integrity_item_outdated_format_version:${E}`),...a.ahead.map(E=>`integrity_item_ahead_format_version:${E}`),...zM(l),...d.tracked_path_count>0?[`tracked_runtime_cache_files:${d.tracked_path_count}`]:[],...f!==null&&f.status!=="ok"?[`merge_driver_configuration_${I?"missing":"drift"}:${f.missing_keys.length+f.drifted_keys.length}`]:[],...v.length>0?[`merge_decisions_unreviewed:${v.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],...HM({invalidEvidenceCount:p.invalid_evidence_count,missingHistoryReferenceCount:y.length})],P=[...new Set(x)].sort((E,$)=>E.localeCompare($)),S=P.filter(E=>!E.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:S.length===0?"ok":"warn",ok:S.length===0,details:{checked_item_files:i.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:i.unreadable.length,item_conflict_markers:i.conflictMarkers.length,item_parse_failures:i.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:a.outdated.length,item_ahead_format_version:a.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:d.tracked_path_count,merge_driver_configuration:f===null||f.status==="ok"?0:f.missing_keys.length+f.drifted_keys.length,pending_merge_decisions:v.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:p.invalid_evidence_count,missing_merge_receipt_history_references:y.length,accepted_legacy_merge_receipt_references:g.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:g.acceptedDispositionCount},item_unreadable:i.unreadable,item_conflict_markers:i.conflictMarkers,item_parse_failures:i.parseFailures,item_outdated_format_version:a.outdated,item_ahead_format_version:a.ahead,hierarchy_integrity:{...l,relations:qt(l.relations,$r)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:d.tracker_relative_root,tracked_paths:d.tracked_paths,tracked_path_count:d.tracked_path_count,remediation_command:d.remediation_command},merge_driver_configuration:f===null?null:{...f,required:r},pending_merge_decision_items:[...new Set(v.map(E=>E.item_id))].sort((E,$)=>E.localeCompare($)),lossless_merge_receipt_items:[...new Set(A.map(E=>E.item_id))].sort((E,$)=>E.localeCompare($)),invalid_merge_receipt_evidence_details:p.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:p.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:y.slice(0,Qn),missing_merge_receipt_history_reference_details_truncated:y.length>Qn}},warnings:P,gitWorkspaceRoot:u,pendingMergeReceipts:b}}function BM(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function GM(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:BM(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function VM(e,t){let n=ae(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function WM(e){let n=ae(e.status)?.toLowerCase();return n==="failed"?"failed":n==="applied"?"applied":"pending"}function KM(e){return ae(e.reason)??ae(e.error)??ae(e.message)}function xu(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function JM(e){let t=[],n=[],r=[];e.forEach((i,s)=>{let a=VM(i.definition,s),c=WM(i.definition);if(c==="applied"){t.push({layer:i.layer,name:i.name,id:a,status:c});return}if(c==="failed"){r.push({layer:i.layer,name:i.name,id:a,status:c,reason:KM(i.definition)});return}n.push({layer:i.layer,name:i.name,id:a,status:c})}),t.sort(xu),n.sort(xu),r.sort(xu);let o=[...r.map(i=>`extension_migration_failed:${i.layer}:${i.name}:${i.id}`),...n.map(i=>`extension_migration_pending:${i.layer}:${i.name}:${i.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:o}}function YM(e,t,n,r,o,i,s,a,c){let l=[...new Set(e)].sort((y,b)=>y.localeCompare(b)),d=[...new Set(l.map(y=>Zw(y)))].sort((y,b)=>y.localeCompare(b)),u=l.filter(y=>y.startsWith("extension_capability_unknown:")).length,f=c.length>0,p=f?"partial":"full",m=[],g=kw(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return g&&m.push(g),t>0&&m.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&m.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&m.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),o>0&&m.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&m.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ve.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&m.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&m.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),f?m.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):s.length>0&&m.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),m.length===0&&m.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:o,managed_extension_entries_count:i,unmanaged_loaded_extension_count:s.length,unmanaged_loaded_extensions:s,unmanaged_expected_extension_count:a.length,unmanaged_expected_extensions:a,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:p,update_health_partial:f,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:m}}async function XM(e,t,n){let r=await Sw(en(e)),o=await fo({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),i=o.loaded.map(S=>GM(S)),s=await Eh(o.loaded,en(e)),a=await po({...o,loaded:o.loaded}),[c,l]=await Promise.all([oi(o.roots.project),oi(o.roots.global)]);await Ew(e,a.registrations.migrations);let d=JM(a.registrations.migrations),u={failed:a.failed,warnings:a.warnings,hook_counts:a.hook_counts,command_override_count:a.command_override_count,command_handler_count:a.command_handler_count,parser_override_count:a.parser_override_count,preflight_override_count:a.preflight_override_count,service_override_count:a.service_override_count,renderer_override_count:a.renderer_override_count,registration_counts:a.registration_counts,registrations:a.registrations,migration_status:d.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:l.path,count:l.state.entries.length,entries:l.state.entries}}},f=new Set(c.state.entries.map(S=>ci(S.name))),p=new Set(l.state.entries.map(S=>ci(S.name))),m=[...new Map(o.loaded.filter(S=>!(S.layer==="project"?f:p).has(ci(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,E)=>{let $=`${S.layer}:${S.name}`,Q=`${E.layer}:${E.name}`;return $.localeCompare(Q)}),g=m.map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),y=m.filter(S=>Vw(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),b=m.filter(S=>!Vw(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,E)=>S.localeCompare(E)),v=b.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${b.length}`]:[],A=[...r.warnings,...o.warnings,...u.warnings,...d.warnings,...c.warnings,...l.warnings,...v,...s.warnings],I=mu(A),x=_u(),P=YM(A,o.failed.length,a.failed.length,d.summary,c.warnings.length+l.warnings.length,c.state.entries.length+l.state.entries.length,g,y,b);return{check:{name:"extensions",status:A.length===0?"ok":"warn",ok:A.length===0,details:{...o,loaded:i,warnings:A,activation:u,author_manifest:r,triage:P,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:I,host_version_census:s}},warnings:A}}function ZM(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function qt(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function QM(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function Tu(e,t){let n=qt(e,t);return{...n,sample:n.sample.map(r=>QM(r))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function e$(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var t$={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:Tu(e.discovered,t),effective:Tu(e.effective,t),loaded:Tu(e.loaded,t),failed:qt(e.failed,t),warnings:W(e.warnings,t),activation:{failed:qt(n.failed,t),warnings:W(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:e$(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:qt(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:W(n.affected_item_ids,t),samples:qt(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:W(e.item_unreadable,t),item_conflict_markers:qt(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:qt(e.history_conflict_markers,t),history_invalid_json:qt(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:W(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:W(e.stale_items_after,t),skipped:e.skipped})};function n$(e,t){let n=t$[e.name];return n?n(e.details,t):e.details}function r$(e){let t=W(e.warnings,$r);return{ok:e.ok,checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:n$(n,$r)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:$r},generated_at:e.generated_at}}function Ww(e){return e.details.skipped===!0}function o$(e){let t=W(e.warnings,$r),n=e.checks.filter(Ww).map(r=>r.name);return{ok:e.ok,checks:e.checks.filter(r=>!Ww(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:$r,omitted_checks:n},generated_at:e.generated_at}}function Kw(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ZM(e,Jw);return{values:n.values,truncated:n.truncated,total:e.length}}function ai(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function i$(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return IM.has(e)?e:null}function Cu(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function s$(e){let t=0,n=0,r=0,o=0,i=0;for(let s of e.split(`
|
|
118
|
+
`)){let a=s.trim();if(a.length!==0){r+=1;try{let c=JSON.parse(a);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let l=Math.max(0,Math.trunc(c.attempts));t+=1,i=Math.max(i,l),l>=Yw&&(o+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:o,maxAttempts:i}}function a$(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function c$(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function l$(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0?void 0:{attempted:!0,...await h$(n)}}function d$(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let o=n.last_successful_flush_at,i=n.last_failed_flush_at,s=i&&(!o||i>o),a=!o,c=t.validEntries>=NM;return(s||a||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function u$(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function f$(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>gh?[`telemetry_schema_version_behind:${t}`]:[]}function p$(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,o=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&!!o&&(!r||o>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function m$(){return{telemetry_disabled:ai("PM_TELEMETRY_DISABLED")||ai("PM_NO_TELEMETRY"),pm_no_telemetry:ai("PM_NO_TELEMETRY"),telemetry_otel_disabled:ai("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ai("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:i$()}}function _$(e,t){return e.telemetry.enabled&&t.validEntries>0}function g$(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function h$(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(RM)});return{probe_url:Cu(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of DM){let o=n.headers.get(r)?.trim();if(o&&o.length>0)return o}})()}}catch(n){return{probe_url:Cu(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function y$(e,t){let n=An(process.cwd()),r=Be.join(n,CM),o=Be.join(n,OM),i=await Z(r),s=i!==null,a=i?Buffer.byteLength(i,"utf8"):0,c=i?s$(i):a$(),l=await Z(o),{runtimeState:d,stateParseFailed:u}=c$(l),f=e.telemetry.endpoint.trim(),p=Cu(f),m=await l$(e,t.checkTelemetry),g=[];u&&g.push("telemetry_state_invalid_json"),g.push(...d$(e,c,d),...u$(m),...f$(m),...p$(e,d));let y=_$(e,c),b=typeof d.pending_otel_spans=="number"?d.pending_otel_spans:0;return{check:{name:"telemetry",status:g.length===0?"ok":"warn",ok:g.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:p,global_pm_root:n,queue_path:r,queue_exists:s,queue_entries:c.validEntries,queue_draining:g$(y,g),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:a,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Yw,queue_max_attempts:c.maxAttempts,runtime_state_path:o,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:b,last_otel_attempt_at:d.last_otel_attempt_at??null,last_otel_success_at:d.last_otel_success_at??null,last_otel_failure_at:d.last_otel_failure_at??null,last_otel_failure_error:d.last_otel_failure_error??null,endpoint_probe:m??{attempted:!1},env_overrides:m$()}},warnings:g}}async function w$(e){let t;try{t=await Eg(e)}catch(r){let o=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:o,pm_root:e}},warnings:[`locks_scan_failed:${o}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function b$(e){let t="metadata",n=e.items,r=await Jn(e.pmRoot,n,{cacheHitVerification:t}),o=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((b,v)=>b.localeCompare(v)),i=[],s=[];if(o.length>0){n=await Xn(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await Jn(e.pmRoot,n),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,A)=>v.localeCompare(A));let b=new Set(i);s=o.filter(v=>!b.has(v))}let{missingStreams:a,unreadableStreams:c,hashMismatches:l,chainMismatches:d,versionSkews:u,driftedItems:f,workspaceStateMismatches:p,workspaceStateMissing:m,workspaceStateUnreadable:g}=r,y=[...a.map(b=>`history_drift_missing_stream:${b}`),...c.map(b=>`history_drift_unreadable_stream:${b}`),...l.map(b=>`history_drift_hash_mismatch:${b}`),...d.map(b=>`history_drift_chain_mismatch:${b}`),...u.map(b=>`history_drift_version_skew:${b}`),...p.map(b=>`history_drift_workspace_state_mismatch:${b}`),...m.map(b=>`history_drift_workspace_state_missing:${b}`),...g.map(b=>`history_drift_workspace_state_unreadable:${b}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:o.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:o.length>0,reason:o.length>0?"cached_corruption_candidate":null,candidate_items:o,confirmed_items:i,resolved_false_positive_items:s,authoritative_item_source:o.length>0},drifted_items:f,counts:{drifted:f.length,missing_streams:a.length,unreadable_streams:c.length,hash_mismatches:l.length,chain_mismatches:d.length,version_skews:u.length,workspace_state_mismatches:p.length,workspace_state_missing:m.length,workspace_state_unreadable:g.length},missing_streams:a,unreadable_streams:c,hash_mismatches:l,chain_mismatches:d,version_skews:u,workspace_state_mismatches:p,workspace_state_missing:m,workspace_state_unreadable:g}},warnings:y}}function v$(e,t){let n=Rr(e),r=qo(n.settings),o=Go(n.settings,t),i=r.active?Dr(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:o,runtimeEmbeddingIdentity:i,semanticRuntimeAvailable:!!(r.active&&o.active)}}function k$(){return{refreshed:[],skipped:[],warnings:[]}}async function E$(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?k$():mh(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function S$(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&Vo(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function x$(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function T$(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function A$(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:cd(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:cd(r,e.vector_store?.adapter??null)}}function I$(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function C$(e,t,n){return e.enabled&&n.length>0&&t}async function O$(e,t,n,r,o){let i=v$(t,e),s=await Jo(e),a=i.semanticRuntimeAvailable?Td(n,s.entries):[],c=await E$({pmRoot:e,snapshot:i,refreshPolicy:r,staleBefore:a}),l=await Jo(e),d=i.semanticRuntimeAvailable?Td(n,l.entries):[],u=!i.runtimeDefaults.auto_ollama_defaults_applied,f=S$({strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,ledgerBefore:s,runtimeEmbeddingIdentity:i.runtimeEmbeddingIdentity}),p=x$({ledgerBefore:s,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:i.semanticRuntimeAvailable,embeddingIdentityChanged:f,staleAfter:d}),m=Kw(a,o),g=Kw(d,o),y=C$(r,i.semanticRuntimeAvailable,a);return{check:{name:"vectorization",status:p.length===0?"ok":"warn",ok:p.length===0,details:{semantic_runtime_available:i.semanticRuntimeAvailable,compatibility_mode_auto_defaults:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:i.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:i.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:i.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:I$(r),...A$(t,i),embedding_identity_changed:f,embedding_identity_before:s.embedding??null,embedding_identity_runtime:i.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(s.entries).length,stale_items_detail_mode:o?"full":"summary",stale_items_summary_limit:Jw,stale_items_before_total:m.total,stale_items_before:m.values,stale_items_before_truncated:m.truncated,refresh_attempted:y,refresh_skipped_reason:T$(r,i.semanticRuntimeAvailable,a),refresh_result:c,ledger_entries_after:Object.keys(l.entries).length,stale_items_after_total:g.total,stale_items_after:g.values,stale_items_after_truncated:g.truncated}},warnings:p}}function R$(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function N$(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new w("--check-only cannot be combined with --refresh-vectors",h.USAGE);if(n&&e.noRefresh===!0)throw new w("--no-refresh cannot be combined with --refresh-vectors",h.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var D$=new Set(["extensions","locks","search"]);function P$(e){let t=new Set(Ia.filter(o=>o.length>0)),n=new Set,r=new Set(Object.values(Oe));for(let o of e.folders)t.has(o)&&!r.has(o)||(t.delete(o),n.add(o));for(let o of D$)t.delete(o),n.add(o);return{requiredDirs:[...t].sort((o,i)=>o.localeCompare(i)),optionalDirs:[...n].sort((o,i)=>o.localeCompare(i)),optionalDirSet:n}}async function L$(e,t,n){let{requiredDirs:r,optionalDirs:o,optionalDirSet:i}=P$(t),s=[],a=[],c=[];for(let l of[...r,...o]){let d=Be.join(e,l);c.push(...await Ue({path:d,scope:"project"})),!await Qw(d)&&(i.has(l)?a.push(l):s.push(l))}return{requiredDirs:r,optionalDirs:o,missingRequiredDirs:s,missingOptionalDirs:a,missingDirs:n?[...s,...a]:[...s],hookWarnings:c}}function M$(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function $$(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?jo(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):Xn(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Au(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function F$(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function j$(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function U$(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var eb=e=>e.unknown_event_count??0,tb=e=>e.actionable_unknown_event_count??eb(e);function z$(e,t,n,r,o,i,s){let a=eb(r),c=tb(r),l=a>0,d=c>0,u=o.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!u,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...l?{author_attribution:r}:{},...u?{stale_in_progress:o}:{},...i.length>0?{provenance_resolver_outcomes:i}:{},...s.length>0?{provenance_invalid_values:s}:{},...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function H$(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function q$(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function B$(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function G$(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.over_threshold.map(t=>`history_stream_over_compact_threshold:${t}`),...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function V$(e){let t=new Map;for(let[o,i]of Object.entries(e.remediationSources))for(let s of i)t.has(s)||t.set(s,o);let n=new Map(e.checks.map(o=>[o.name,o]));return e.warnings.map(o=>{let i=t.get(o)??"integrity",s=Od(o)?.code??Zw(o),a=n.get(i)?.details,l=(typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{})[s],d=Xw(o,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:o,code:s,check:i,severity:d,...typeof l=="string"?{remediation:l}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function W$(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function K$(e){for(let t of e.checks){let n=Rd(e.remediationSources[t.name]);W$({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function J$(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(s=>typeof s=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(s=>Array.isArray(s)?s:[])),o=new Map;for(let s of e.pendingMergeReceipts){if(s.evidence_source!=="clone_local")continue;let a=o.get(s.item_id)??[];a.push(s),o.set(s.item_id,a)}let i=[];for(let s of n){if(r.has(s))continue;let a=o.get(s);if(!(!a||a.length===0))try{(await Mr(s,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:a}},e.global)).merge_receipt_proof?.trusted&&i.push(s)}catch{}}return[...new Set(i)].sort((s,a)=>s.localeCompare(a))}function Y$(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,o)=>r.localeCompare(o)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function X$(e,t,n){let r=e.warning_count??e.warnings.length,o={...e,warning_count:r,warning_limit:Qn,warnings_truncated:r>Qn,warnings:e.warnings.slice(0,Qn),findings:(e.findings??[]).filter(s=>e.warnings.slice(0,Qn).includes(s.warning)||e.failed_because.includes(s.warning))},i=n?o$(o):t.brief===!0?r$(o):o;return{...i,warning_count:r,warning_limit:Qn,warnings_truncated:r>i.warnings.length,...i.projection?{projection:{...i.projection,warning_count:r,warnings_truncated:r>i.warnings.length}}:{}}}async function Ou(e,t={}){let n=te(process.cwd(),e.path);await Ie(n);let r=be(n),{settings:o,warnings:i}=await pn(n),s=[...new Set(i)],a=de(o,K()),c=t.strictDirectories===!0,l=N$(t),d=await L$(n,a,c),u=R$(o),f=await y$(o,{checkTelemetry:t.checkTelemetry===!0}),p=await XM(n,o,!!e.noExtensions),m=M$(t),g=[],y=await $$({pmRoot:n,settings:o,typeRegistry:a,skipPolicy:m,itemReadWarnings:g}),b=y,v=da(Rt(o.schema),y),A=[...u,...ua(v)],I=m.skipDrift?{warnings:[]}:await $s({pmRoot:n,settings:o,itemIds:y.map(Sa=>Sa.id),commandLabel:"health"}),x=await MM(n,o.history.compact_policy,await PM(n)),P=await ra(n,20,t.verboseAuthorEvents===!0),S=tb(P),E=S>0?[`history_unknown_author_events:${S}`]:[],$=H$(await Dd(n,y,{in_progress_status:o.schema.workflow.in_progress_status,threshold_hours:o.mutation_guard.stale_in_progress_hours})),Q=await Cw(n),M=Q.outcomes,R=Q.invalid_values,ee=Q.warnings,De=await w$(n),Pe=m.skipIntegrity?{...Au("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await qM(n,a.type_to_folder,o.schema,t.requireMergeDrivers===!0,y),nt=m.skipDrift?Au("history_drift"):await b$({pmRoot:n,items:b,settings:o,typeRegistry:a,itemReadWarnings:g}),Ur=[...new Set(g)],Zb=await J$({gitWorkspaceRoot:Pe.gitWorkspaceRoot,pendingMergeReceipts:Pe.pendingMergeReceipts,historyDriftCheck:nt,global:e});Y$(nt,Zb);let va=m.skipVectors?Au("vectorization"):await O$(n,o,b,l,t.verboseStaleItems===!0),ka=[F$(r,o,s),j$(d,c),U$(A,v),f.check,p.check,z$(y,o,x,P,$.scan,M,R),De.check,Pe.check,nt.check,va.check],Ea=q$({directoryState:d,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:Ur,telemetryCheck:f,extensionCheck:p,historyPolicyWarnings:I.warnings,historySummary:x,authorAttributionWarnings:E,staleInProgressWarnings:$.warnings,provenanceWarnings:ee,locksCheck:De,integrityCheck:Pe,historyDriftCheck:nt,vectorizationCheck:va}),Vu=G$({directoryState:d,normalizedSettingsReadWarnings:s,settingWarnings:A,normalizedItemReadWarnings:Ur,telemetryCheck:f,extensionCheck:p,historyPolicyWarnings:I.warnings,historySummary:x,authorAttributionWarnings:E,staleInProgressWarnings:$.warnings,provenanceWarnings:ee,locksCheck:De,integrityCheck:Pe,historyDriftCheck:nt,vectorizationCheck:va});K$({checks:ka,remediationSources:Vu,historyDriftedCount:B$(nt),overThresholdCount:x.over_threshold.length});let Wu=Ea.filter(Sa=>!Xw(Sa,t.requireMergeDrivers===!0)),Qb=V$({warnings:Ea,checks:ka,remediationSources:Vu,requireMergeDrivers:t.requireMergeDrivers===!0}),ev={ok:Wu.length===0,checks:ka,warnings:Ea,findings:Qb,failed_because:Wu,generated_at:F()};return X$(ev,t,m.summaryMode)}import Bu from"node:fs/promises";import{realpathSync as sj}from"node:fs";import{execFile as aj}from"node:child_process";import Ge from"node:path";import{promisify as cj}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var Z$=["metadata","resolution"],Ru=["metadata","resolution","estimates","lifecycle"],Q$="completed";function Nu(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function nb(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function rb(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=nb(n.close_reason)??Q$;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Nu(r)}`,gate:"resolution"})}return t}function ob(e){let t=[];for(let n of e){let r=nb(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Nu(r)}`,gate:"metadata"})}return t}function ib(e,t){return e.map(n=>{let r=K_(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function sb(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function ab(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Nu(n.path)}`})}return t}function cb(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new w(`--fix-scope values must not be empty. Supported values: ${Ru.join(", ")}.`,h.USAGE);return new Set(Z$)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(Ru.includes(o)){n.add(o);continue}throw new w(`Unknown --fix-scope value "${r}". Supported values: ${Ru.join(", ")}.`,h.USAGE)}return n}function lb(e,t){let n=[],r=[];for(let o of e)o.gate!==void 0&&!t.has(o.gate)?r.push(o):n.push(o);return{applicable:n,gated:r}}function li(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var eF=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function tF(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=eF.exec(n);if(!r)return null;let o=r[1],i=o.toUpperCase(),s=o.slice(0,o.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(o.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${i}`)||l.includes(`ISSUE CODE \`${i}\``)||l.includes(`\`${i}\``)||l.includes(`[${i}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?i:null}function db(e){return typeof e=="string"&&e.trim().length>0}function ub(e,t={}){let n=new Map;for(let o of e){if(typeof o.title!="string"||db(o.duplicate_of))continue;let i=tF(o.title,{...t,evidenceText:o.body});if(i===null)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(a=>a.id===o.id)||s.push({id:o.id,title:o.title,parent:db(o.parent)?o.parent.trim():null})}let r=[];for(let[o,i]of n){if(i.length<2)continue;let s=new Set(i.map(l=>l.id.toLowerCase())),a=i.filter(l=>l.parent===null||!s.has(l.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((l,d)=>l.id.localeCompare(d.id));r.push({code:o,count:c.length,ids:c.map(l=>l.id),titles:c.map(l=>l.title)})}return r.sort((o,i)=>o.code.localeCompare(i.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function fb(e){let t=new Map;for(let r of e){let o=t.get(r.item_type);o||(o=new Map,t.set(r.item_type,o)),o.set(r.field,(o.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r),i={};for(let s of[...o.keys()].sort((a,c)=>a.localeCompare(c)))i[s]=o.get(s);n[r]=i}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var pb=3;function mb(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function _b(e,t,n=pb){let r=Number.isFinite(n)&&n>=1?Math.floor(n):pb,o=new Map;for(let i of t){let s=mb(i);if(s.length===0)continue;let a=o.get(s);a?a.push(i):o.set(s,[i])}return e.map(i=>{let s=(o.get(mb(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function gb(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var nF=/^[a-z][a-z0-9+.-]+:\/\//i;function di(e){return nF.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function rF(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function hb(e){return`${e.item_id} ${e.link_kind}`}function yb(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=rF(o.classification,r.classification),o.owners.set(hb(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[hb(r),r]])})}return[...n.entries()].sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({path:r,classification:o.classification,items:[...o.owners.values()].map(i=>{let s=t(i.item_id);return{id:i.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:i.link_kind}}).sort((i,s)=>{let a=i.id.localeCompare(s.id);return a!==0?a:i.field.localeCompare(s.field)})}))}function oF(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function wb(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${oF(r.title)}"`);return t}import Fr from"node:fs/promises";import jr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function iF(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await Fr.readdir(jr.join(e,o))}catch{return}for(let s of i)for(let a of Nt)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${o}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((o,i)=>o.relativePath.localeCompare(i.relativePath))}function sF(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Me(t);if(s){i.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{i.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&o.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function Du(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function aF(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Fr.readdir(jr.join(e,"history"))}catch{return n}for(let o of r.sort((i,s)=>i.localeCompare(s))){if(!o.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await Fr.readFile(jr.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:Du("history stream",s)});continue}sF({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function bb(e){let t=Me(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function cF(e){let t=[],n=0,r=null;try{r=await Z(be(e))}catch(i){n+=1,t.push({path:"settings.json",detail:Du("configuration file",i)})}if(r!==null){n+=1;let i=bb(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await Fr.readdir(jr.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of o.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let s;try{s=await Fr.readFile(jr.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:Du("configuration file",c)});continue}let a=bb(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function vb(e,t,n,r={}){let o=await iF(e,n),i=new Set(o.map(u=>u.id)),s=new Map;for(let u of o){let f=s.get(u.id);f===void 0?s.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((p,m)=>p.localeCompare(m))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(o.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=jr.join(e,u.relativePath);return $e(await Fr.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await aF(e,i),d=await cF(e);return{item_files_on_disk:o.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import lF from"node:fs/promises";import lt from"node:path";import dF from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var uF=["path","scope","note"],fF=["pattern","glob","path","scope","note"],pF=["path"],mF=["from","to"],_F=new Set(["note","scope"]);function Eb(e){let t=e??"project";if(!Da.includes(t))throw new w(`Invalid scope "${e}". Valid scopes: ${Da.join(", ")} (default: project).`,h.USAGE);return t}function Pu(e){if(e.startsWith("```")||e.includes(`
|
|
119
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||yl(e)}function gF(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function hF(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Pu(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let i=e.slice(t+2,-1).trim();if(i.length>0&&gF(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function yF(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=hF(r);if(i!==void 0)return[i]}v_(r,"--add",`${t} path`,Pu(r));let o=Pu(r)?Sr(n,"--add"):{path:r};if(xr(o,"--add",uF),!o.path)throw new w(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return[{path:o.path,scope:Eb(o.scope),note:o.note?.trim()||void 0}]}):[]}function wF(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Sr(n,"--add-glob");xr(r,"--add-glob",fF);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new w("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:o,scope:Eb(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function bF(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new w("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Sr(n,"--remove"),o=Object.keys(r).filter(i=>_F.has(i.toLowerCase()));if(o.length>0)throw new w(`--remove identifies a linked artifact by path only and does not accept ${o.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,h.USAGE);if(xr(r,"--remove",pF),!r.path)throw new w("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function vF(e){return e?e.map(t=>{let n=Sr(t,"--migrate");xr(n,"--migrate",mF);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new w("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:o}}):[]}function ui(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function kF(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>ui(i.path,n))),o=[...new Set(t.map(i=>ui(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new w(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,h.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function fa(e){return e.split(lt.sep).join("/")}function Lu(e,t,n=process.cwd()){let r=e.trim();if(di(r))return r;if(lt.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return fa(r.replaceAll("\\",lt.sep));let o=lt.relative(t,n);return o.startsWith(`..${lt.sep}`)||o===".."||lt.isAbsolute(o)?fa(lt.normalize(r)):fa(lt.relative(t,lt.resolve(n,r)))}async function EF(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=lt.isAbsolute(o.pattern),s=await dF(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Lu(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)r.push({path:c,scope:o.scope,note:o.note})}return r}function SF(e,t,n){if(t===void 0)return e;if(!n)throw new w("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",h.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function xF(e){return`${e.path}::${e.scope}`}function Sb(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function xb(e){return[...new Map(e.map(t=>[xF(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function TF(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],i=[],s=[];for(let a of n){if(di(a)){s.push(a.trim());continue}let c=lt.isAbsolute(a)?a:lt.resolve(t,a);try{(await lF.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&ut(l)){o.push(a);continue}i.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:i,remote_references:s}}function AF(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=ui(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=ui(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>ui(s,r)),count:o}}function IF(e,t,n,r){for(let i of t)e.some(s=>s.path===i.path&&s.scope===i.scope)||e.push(i);if(n.length>0)for(let i=e.length-1;i>=0;i-=1)n.includes(e[i].path)&&e.splice(i,1);let o=xb(e);return r?o:Sb(o)}async function kb(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await TF(t,e.workspaceRoot):void 0}}async function pa(e,t,n,r){let{metadataKey:o}=r,i=Eo(),s=te(process.cwd(),n.path),a=en(s),c=process.cwd();await Ie(s);let l=await oe(s),d=de(l,K()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),p=await i.resolveList(t.remove,"--remove"),m=await i.resolveList(t.migrate,"--migrate"),g=yF(u,r.bareNoun).map(M=>({...M,path:Lu(M.path,a,c)})),y=wF(f),b=await EF(y,a,c),v=SF([...g,...b],t.note,g.length>0||y.length>0),A=bF(p).map(M=>Lu(M,a,c)),I=vF(m);if(kF(v,A,I),!(v.length>0||A.length>0||I.length>0)){let M=await Ze(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!M)throw new w(`Item ${e} not found`,h.NOT_FOUND);let ee=(await He(M,{schema:l.schema})).document.metadata[o]??[];return kb({id:M.id,artifacts:ee,changed:!1,options:t,workspaceRoot:a})}let P=Ye(t.author,l.author_default),S=await Uo({pmRoot:s,settings:l,id:e,op:r.op,author:P,message:t.message,force:t.force,skipNoop:!0,mutate(M){let R=M.metadata,ee=R[o]??[],De=[...ee],Pe=AF(De,v,A,I),nt=IF(De,Pe.adds,Pe.removes,r.supportsAppendStable&&t.appendStable===!0);nt.length>0?R[o]=nt:delete R[o];let Ur=!rt(ee,nt);return{changedFields:Ur?[o]:[],warnings:Ur&&Pe.count>0?[`path_migrations_applied:${Pe.count}`]:[]}}}),E=S.item[o]??[],$=S.warnings.find(M=>M.startsWith("path_migrations_applied:")),Q=$?Number($.slice(24)):0;return kb({id:S.item.id,artifacts:E,changed:S.changedFields.includes(o),migrationsApplied:Q,options:t,workspaceRoot:a})}function ma(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Tb(e,t,n){let r=await pa(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ma(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();async function Ab(e,t,n){let r=await pa(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ma(r,"files")}import{readFileSync as CF}from"node:fs";import _a from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var OF=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ob=new Set(["--pm-path","--path","--author"]),RF={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},NF=new Set(["-p","--package"]),DF=new Set(["-c","--call"]),PF=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),LF=new Set(["-C","--prefix","--userconfig","--cache"]);var MF=new Set(["exec","x"]);function $F(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function FF(e,t=process.cwd()){let n=jF(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(Ib(r)||Cb(r,t))return o;if(r==="node"&&o[0]&&Cb(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?Mu(o):r==="pnpm"?HF(o):r==="npm"?qF(o):null;return i&&(Ib(i.command)||zF(i.command))?i.args:null}var Rb=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of $F(i)){let c=FF(a),l=c?BF(c):null,d=l&&OF.has(l.subcommand)?GF(l.remaining,RF[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${o}-`)===!0&&u.length>o.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function jF(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Ib(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function UF(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function zF(e){let t=UF(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Cb(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=_a.resolve(t,e);try{return JSON.parse(CF(_a.join(_a.dirname(_a.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Mu(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let i=o[1];return i?{command:i,args:e.slice(t+1)}:null}if(DF.has(r)){t+=1;break}t+=NF.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Nb(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function HF(e){let t=Nb(e,PF);return t?.subcommand!=="dlx"?null:Mu(t.args)}function qF(e){let t=Nb(e,LF);return!t||!MF.has(t.subcommand)?null:Mu(t.args)}function BF(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ob.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function GF(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Ob.has(r)||t.has(r))&&(n+=1)}}import{execFile as VF}from"node:child_process";import{readFile as WF}from"node:fs/promises";import KF from"node:path";import{promisify as JF}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var YF=JF(VF),$u=1,XF="linked-test-trust.json";function ZF(e){return KF.join(Gi(e),XF)}function Db(){return{version:$u,acknowledged:{}}}async function QF(e){try{let t=JSON.parse(await WF(ZF(e),"utf8"));return t.version!==$u||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Db():{version:$u,acknowledged:t.acknowledged}}catch{return Db()}}async function Pb(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await YF("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Lb(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function ej(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&dt(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function fi(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function tj(e){return ye(N({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}function nj(e,t,n){let r=tj(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let i=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!ej(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...fi(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...fi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...fi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...fi(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...fi(o,t)}}async function Mb(e,t,n){let r=await QF(e);return t.map(o=>nj(o,n,r))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function $b(e){return e.includeBody?Xn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Fo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var rj=5;async function Fb(e,t,n){let r=await Jn(e,t),i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),s=n?Number.POSITIVE_INFINITY:rj,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function Fu(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),o=[n],i=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&o.length>1)return o.push(n),!0;if(!i.has(c)){if(i.add(c),o.push(c),s(c))return!0;o.pop(),i.delete(c)}}return!1};return s(n)?[...o]:[...e,n]}function oj(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function ij(e,t,n,r){for(let o of e.dependencies??[]){if(typeof o!="object"||o===null||typeof o.id!="string")continue;let i=r.resolve(o.kind);if(!i?.hierarchy)continue;let s=n.get(o.id.toLowerCase());s&&(i.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function jb(e,t=Ht()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),r=new Map(e.map(o=>[o.id,[]]));for(let o of[...e].sort((i,s)=>i.id.localeCompare(s.id))){let i=r.get(o.id),s=oj(o.parent,n);s&&i.push(s),ij(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function Ub(e,t,n=Ht()){let r=si(e,s=>t?Ma(s,t):s==="closed"||s==="canceled",n),o=jb(e,n),i=r.cycles.map(s=>s.item_ids);return{cycle_count:i.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(i.flat())].sort(),cycle_sample_paths:i.map(s=>Fu(s,o).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function yn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ju(e){return yn(e).replace(/\/+$/,"")}function Ct(e){let t=ae(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d466293-869d-54bb-b07d-facb3be51e8c")}catch{}})();var lj=["src","tests","docs"],dj=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],uj=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),fj=["resolution","expected_result","actual_result"],pj=["default","tracked-all","tracked-all-strict"],zb=["core","strict","custom"],ya=["off","warn","error"],Hu=["author","acceptance_criteria","estimated_minutes","close_reason"],Gb=[...Hu,"reviewer","risk","confidence","sprint","release"],Gu=Array.from(new Set(Gb)),mj={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},_j={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},gj={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},hj={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},yj={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},wj=32*1024*1024,bj=1e4,Vb=40,Vt=5,vj=4096,kj=255,Ej=cj(aj);function Wb(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Wb(r):r);return t}function Sj(e){return{...e,checks:e.checks.map(t=>({...t,details:Wb(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function ba(e,t){return Yt(e,t)??e}function pi(e,t){return t.terminal_statuses.has(ba(e,t))}function wn(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ga(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function xj(e){let t=wn(Oa),n={blocked_reason:wn(vn.blocked_reason),resolution:wn(vn.resolution),actual_result:wn(vn.actual_result)},r=wn(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:wn(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:wn(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:wn(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ga(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:ga(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ga(o.resolution,n.resolution)?"default":"settings",actual_result:ga(o.actual_result,n.actual_result)?"default":"settings"}}}function Tj(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(zb.includes(t))return t;throw new w(`Unknown --metadata-profile value "${e}". Supported values: ${zb.join(", ")}.`,h.USAGE)}function Aj(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ya.includes(t))return t;throw new w(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ya.join(", ")}.`,h.USAGE)}function Ij(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ya.includes(t))return t;throw new w(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ya.join(", ")}.`,h.USAGE)}function Cj(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>mj[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function Oj(e,t,n){let r=Cj(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Hu],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Gb],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Hu],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Rj=new Set(["acceptance_criteria","estimated_minutes"]);function Nj(e,t,n,r){return!r&&Rj.has(t)&&pi(e.status,n)?!1:t==="author"?!ae(e.author):t==="acceptance_criteria"?!ae(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?ba(e.status,n)===n.close_status&&!ae(e.close_reason):t==="reviewer"?!ae(e.reviewer):t==="risk"?!ae(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ae(e.confidence):t==="sprint"?!ae(e.sprint):!ae(e.release)}function Dj(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new w(`Unknown --scan-mode value "${e}". Supported values: ${pj.join(", ")}.`,h.USAGE)}function Pj(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ge.resolve(t);let n=Ge.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ge.dirname(Ge.dirname(n));let o=Ge.resolve(process.cwd()),i=Hb(n),s=Hb(o),a=Ge.relative(i,s);return a.length===0||!a.startsWith("..")&&!Ge.isAbsolute(a)?n:o}function Hb(e){try{return sj.native(e)}catch{return Ge.resolve(e)}}function Lj(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Kb(e,t,n){let r=t.length>0?Ge.join(e,t):e,o;try{o=await Bu.readdir(r,{withFileTypes:!0})}catch(i){if(j(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?Ge.join(t,i.name):i.name;if(i.isDirectory()){if(uj.has(i.name))continue;await Kb(e,s,n);continue}i.isFile()&&n.push(yn(s))}}async function qb(e){let t=[];for(let n of lj)await Kb(e,n,t);for(let n of dj){let r=Ge.join(e,n);try{(await Bu.stat(r)).isFile()&&t.push(yn(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function Mj(e){try{let{stdout:t}=await Ej("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:wj,windowsHide:!0,timeout:bj}),n=t.split("\0").map(r=>yn(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function $j(e,t){let n=new Set,r=ju(tr);r.length>0&&n.add(r);let o=ju(Ge.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function Bb(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Fj(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await Mj(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await qb(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await qb(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function le(e,t=Vt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function bn(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=le(e,Vb);return{values:n.values,truncated:n.truncated,total:e.length}}var jj={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},Uj={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function zj(e){let t=e.missing_fields.map(n=>`${jj[n]} "${Uj[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Hj(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,o=r?n.filter(s=>typeof s=="string"):wh(t);if(o.length===0)return;let i=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:o,...i?{fix_hints_truncated:!0}:{}}}function qj(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var Bj="validate_metadata_duplicate_issue_codes";function Gj(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Vt,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${Bj}:${e.length}`]}}function Vj(){return Object.fromEntries(Gu.map(e=>[e,[]]))}function Wj(e,t,n){let r=Vj();for(let o of e)for(let i of Gu)Nj(o,i,t,n)&&r[i].push(o.id);return r}function Kj(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${_j[o]}:${i.length}`)}return r.push(...n),r}function Jj(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=gj[r];n[s]=i}return n}function Yj(e,t,n){let r=[];for(let o of e.required_fields){let i=t[o];if(i)for(let s of i){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:o})}}return r}function Xj(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=hj[o],a=yj[o];if(!s||!a)continue;let c=le(i,r?i.length:Vt);e[s]=c.values,e[a]=c.truncated}}function Zj(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:ae(n.get(o)?.resolution)})):[]}function Qj(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:ae(n.get(o)?.type)})):[]}function e1(e,t,n,r,o){let i=new Map(e.map(b=>[b.id,b])),s=t.profile==="strict",a=Wj(e,n,s),c=ub(e,{configuredPrefixes:o}),l=Gj(c,r),d=Kj(t,a,l.warnings),u=Jj(t,a),f=Yj(t,a,i),p=fb(f),m={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Gu],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(m.configured_custom_required_fields=[...t.configured_custom_fields]),Xj(m,t,a,r);let g=Zj(t,a,i),y=Qj(t,a,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:m},warnings:d,closeReasonBackfillRows:g,estimateBackfillRows:y}}function t1(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(ba(f.status,t))),i=[],s=[];for(let f of o){let p=fj.filter(m=>!ae(f[m]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:ae(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:Vt,l=le(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>zj(f)),u=le(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:o.length,missing_resolution_items:i.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function n1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function r1(e,t="pm",n=Cn()){let r=new Set(e.map(i=>i.id)),o=[...e].sort((i,s)=>i.id.localeCompare(s.id));return new Map(o.map(i=>{let s=new Set,a=Ct(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=Ct(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>Ct(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=Ct(i.definition_of_ready);return i1(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function o1(e,t,n){let r=Gw(e,n?d=>pi(d,n):void 0),o=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),i=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:Vt,a=le(o,s),c=le(i,s),l=le(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:e.length,dangling_reference_count:o.length+i.length,active_dangling_reference_count:o.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:o.length>0?[`validate_dangling_dependency_references:${o.length}`]:[]}}function i1(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${n1(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(o=>o[1].toLowerCase()))].sort((o,i)=>o.localeCompare(i))}function s1(e){let t=0,n=new Map,r=new Map,o=[],i=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,o.push(d),i.add(d);for(let f of e.get(d)??[])n.has(f)?i.has(f)&&r.set(d,Math.min(r.get(d),n.get(f))):(a(f),r.set(d,Math.min(r.get(d),r.get(f))));if(r.get(d)!==n.get(d))return;let u=[];for(;o.length>0;){let f=o.pop();if(i.delete(f),u.push(f),f===d)break}u.sort((f,p)=>f.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function a1(e,t="pm"){let n=r1(e,t),r=s1(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>Fu(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function c1(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function wa(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function l1(e,t){let n=wa(e).split("/").filter(Boolean),r=wa(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function d1(e,t){let n=wa(t),r=wa(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=l1(e,t);return!i&&!s&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function u1(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function f1(e,t,n){let r=t==="docs_unowned"?"docs":"files",o;return n.flatMap(i=>(r==="docs"?i.docs??[]:i.files??[]).map(s=>({item:i,link:s}))).forEach(({item:i,link:s})=>{if(s.scope!=="project")return;let a=yn(s.path);if(a.length===0||a===e)return;let c=d1(e,a);c!==null&&u1(o,i,c.score)&&(o={item:i,score:c.score,confidence:c.confidence})}),o?{id:o.item.id,type:o.item.type,title:o.item.title,status:o.item.status,confidence:o.confidence}:null}function p1(e,t){return e.map(n=>{let r=c1(n),o=r==="docs_unowned"?"docs":"files",i=f1(n,r,t),s=i?.id??"<id>";return{path:n,classification:r,owner_candidate:i,remediation_hint:`pm ${o} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function m1(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function _1(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=Ct(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function g1(e,t,n,r,o){let i=Ct(t.parent),s=i?n.get(r.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!pi(s.status,o)}}function h1(e,t,n,r){let o=Ct(e.blocked_by),i=Ct(e.blocked_reason),s=i?.toLowerCase(),a=ba(e.status,n),c=[];return t.has(a)?(!o&&!i&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(o&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function y1(e,t,n,r){let o=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!pi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=_1(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=Ct(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&pi(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(g1(c,u,o,i,n))),t){let f=h1(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((p,m)=>p.localeCompare(m))})}}return a}function w1(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function ha(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Uu(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function b1(e,t,n,r,o){let i=[];e.closureLikeRows.length>0&&i.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&i.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&i.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=ha("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=ha("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=ha("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=ha("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=Uu("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=Uu("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=Uu("validate_legacy_hierarchy_parent_divergence",r,o.legacyHierarchyDivergence);return[...i,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...f?[f]:[]]}function v1(e){let t=yn(e);return t.length>vj||t.split(/[\\/]/).some(n=>n.length>kj)}async function k1(e,t){let n=Ge.isAbsolute(t)?t:Ge.resolve(e,t);if(v1(n))return!1;try{let r=await Bu.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Lj(r,["ENOENT","ENOTDIR"])}}async function E1(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(o=>[...(o.files??[]).map(i=>({item:o,artifact:i,link_kind:"files"})),...(o.docs??[]).map(i=>({item:o,artifact:i,link_kind:"docs"}))]);for(let{item:o,artifact:i,link_kind:s}of r){if(i.scope!=="project")continue;if(di(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=yn(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await k1(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function S1(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:$j(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>Bb(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!Bb(p,l)),f={};if(d.length>0){let p=bn(d,i);f.pm_internals={count:d.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function x1(e,t,n,r,o,i,s,a="pm"){let c=y1(e,t,o,i);w1(c);let l=a1(c.activeItems,a),d=Ub(e,o),u=da(o,e,s?Number.POSITIVE_INFINITY:Vt),f=[...b1(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...ua(u)],p=s?Number.POSITIVE_INFINITY:Vt,m=le(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),p),g=le(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),p),y=le(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),p),b=le(l.cycle_item_ids,p),v=le(l.cycle_sample_paths,p),A=le(d.cycle_item_ids,p),I=le(d.cycle_sample_paths,p),x=le(d.cardinality_violation_rows,p),P=le(d.parent_divergence_rows,p),S=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:S?"error":f.length===0?"ok":"warn",ok:!S&&f.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:m.values,active_closure_like_metadata_rows_truncated:m.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:b.values,dependency_cycle_item_ids_truncated:b.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:A.values,parent_cycle_item_ids_truncated:A.truncated,parent_cycle_sample_paths:I.values,parent_cycle_sample_paths_truncated:I.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:P.values,hierarchy_parent_divergence_rows_truncated:P.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:f,terminalParentFixRows:c.terminalParentFixRows}}async function T1(e,t,n,r,o,i){let s=await E1(e,t),a=new Map(e.map(R=>[R.id,R])),c=[...new Set(s.missingLinkedPaths)].sort((R,ee)=>R.localeCompare(ee)),l=await Fj(t,r),d=S1(l,n,t,r,o,i),u=d.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=p1(u,e),p=_b(c,d.candidateFiles),m=new Map(p.map(R=>[R.path,R.classification])),g=p.filter(R=>R.classification==="moved").length,y=s.staleLinkRows.map(R=>({...R,classification:m.get(R.path)??"deleted"})).sort((R,ee)=>R.item_id.localeCompare(ee.item_id)||R.path.localeCompare(ee.path)||R.link_kind.localeCompare(ee.link_kind)),b=[];d.strictModeForcesPmInternals&&b.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&b.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&b.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((R,ee)=>R.localeCompare(ee)),A=bn(v,i),I=bn(c,i),x=bn(u,i),P=bn(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),i),S=i?f:bn(m1(f),!1).values,E=bn(gb(p),i),$=y.map(R=>({item_id:R.item_id,path:R.path,link_kind:R.link_kind,classification:R.classification})),Q=yb($,R=>{let ee=a.get(R);return ee?{type:ee.type,title:ee.title,status:ee.status}:void 0}),M=i?Q:bn(wb(Q),!1).values;return{check:{name:"files",status:b.length===0?"ok":"warn",ok:b.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:Vb,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:o,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:A.total,remote_linked_paths:A.values,remote_linked_paths_truncated:A.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:I.total,missing_linked_paths:I.values,missing_linked_paths_truncated:I.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:E.values,missing_linked_path_classifications_truncated:E.truncated,missing_linked_path_rows_count:Q.length,missing_linked_path_rows:M,orphaned_paths_count:u.length,orphaned_paths_total:x.total,orphaned_paths:x.values,orphaned_paths_truncated:x.truncated,orphaned_path_classifications:P.values,orphaned_path_classifications_truncated:P.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:S}},warnings:b,staleLinkPruneRows:y}}function Jb(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function A1(e,t,n){return`${e}:${t}:${Jb(n)}`}function I1(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=Jb(o.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function C1(e,t,n,r){let o=new Set(e.map(x=>x.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(x=>(x.tests??[]).map(P=>({item:x,linkedTest:P}))),d=await Pb(Lb()),u=await Mb(r,l.map(({linkedTest:x})=>x),d),f=I1(l,u);for(let{item:x,linkedTest:P}of l){if(typeof P.command!="string"||P.command.trim().length===0)continue;i+=1;let S=Rb(P.command,t);if(S.length!==0){s+=S.length;for(let E of S)a.add(E),o.has(E.toLowerCase())||c.push(A1(x.id,E,P.command))}}let p=[...new Set(c)].sort((x,P)=>x.localeCompare(P)),m=[...new Set(p.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,P)=>x.localeCompare(P)),g=[];p.length>0&&g.push(`validate_command_references_stale_pm_ids:${p.length}`),f.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let y=n?Number.POSITIVE_INFINITY:Vt,b=le(p,y),v=le(m,y),A=le([...a].sort((x,P)=>x.localeCompare(P)),y),I=le(f,y);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:A.values,unique_referenced_pm_ids_truncated:A.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:I.values,untrusted_linked_tests_truncated:I.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:m.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:b.values,stale_pm_id_reference_rows_truncated:b.truncated}},warnings:g}}function O1(e,t){let n=ji(e.map(c=>({ref:c.id,version:Fi(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let o=t?Number.POSITIVE_INFINITY:Vt,i=le(n.outdated,o),s=le(n.ahead,o),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:$i,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var qu="pm validate auto-fix";async function R1(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:qu};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new w("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",h.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function zu(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function N1(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>zu(a)===null))try{await R1(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>zu(a)!==null)){let a=zu(s),c=i.get(a);c?c.push(s):i.set(a,[s])}for(let s of i.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Ab(a.item_id,{remove:c,message:qu},t):await Tb(a.item_id,{remove:c,message:qu},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}function D1(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function P1(e,t,n,r){let o=await vb(e,new Set(t.map(y=>y.id)),n,{schema:r.schema,extensionFieldNames:pt(K())}),i=[];o.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${o.unreadable_item_files.length}`),o.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${o.duplicate_item_ids.length}`),o.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${o.history_conflict_marker_streams.length}`),o.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${o.history_unparseable_streams.length}`),o.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${o.resurrected_items.length}`),o.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${o.unparseable_config_files.length}`);let s=i.length,a=await oa(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Zl(e,Ms(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await Et(e),d=l===null?null:await Oo(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await ft(l??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:m}=Es(f);p.length>0&&i.push(`validate_merge_decisions_unreviewed:${p.length}`),D1(i,u.invalid_evidence_count);let g=s>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...o,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(y=>y.item_id))].sort((y,b)=>y.localeCompare(b)),lossless_merge_receipt_count:m.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(m.map(y=>y.item_id))].sort((y,b)=>y.localeCompare(b)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function Gt(e,t,n){n&&Hj(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function L1(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let o=e1(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,Gt(t,o,n)}if(e.requestedChecks.has("resolution")){let o=t1(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,Gt(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=x1(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,Gt(t,o,n),Gt(t,o1(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await T1(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,Gt(t,o,n)}return e.requestedChecks.has("command_references")&&Gt(t,await C1(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&Gt(t,await Fb(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Gt(t,O1(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Gt(t,await P1(e.pmRoot,e.items,de(e.settings,K()).type_to_folder,e.settings),n),t}function M1(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...ob(t.closeReasonBackfillRows)),r.push(...rb(t.resolutionBackfillRows)),r.push(...ib(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...sb(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...ab(t.staleLinkPruneRows)),r}async function $1(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=M1(e,t,n),{applicable:a,gated:c}=lb(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await N1(a,o,i);d.push(...f.applied.map(li)),u.push(...f.failed.map(({fix:p,error:m})=>({...li(p),error:m instanceof Error?m.message:String(m)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,p)=>f.localeCompare(p)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(li),applied_fixes:d,gated_fixes:c.map(f=>({...li(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Yb(e,t,n={}){Cm(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new w("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",h.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new w("--fix-scope requires --auto-fix.",h.USAGE);let o=cb(e.fixScope),i=te(process.cwd(),t.path);await Ie(i);let s=await oe(i),a=Rt(s.schema),c=de(s,K()),l=qj(e),d=[],u=await $b({includeBody:l.has("history_drift")||l.has("metadata"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let $=await ra(i);$.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${$.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=Tj(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),m=Oj(p,f,s.validation.metadata_required_fields),g=xj(s),y=Aj(e.dependencyCycleSeverity),b=Ij(e.parentCycleSeverity),v=Dj(e.scanMode),A=Pj(i),I=await L1({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:A,settings:s,items:u,statusRegistry:a,metadataPolicy:m,lifecyclePatternPolicy:g,dependencyCycleSeverity:y,parentCycleSeverity:b,fileScanMode:v,initialWarnings:[...new Set(d)]}),x=r?await $1(e,I,s,o,t,n):void 0,P=[...new Set(I.warnings)].sort(($,Q)=>$.localeCompare(Q)),E={ok:!I.checks.some($=>$.status==="error"),has_warnings:P.length>0,checks:I.checks,warnings:P,...x!==void 0?{fixes:x}:{},generated_at:F(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...Sj(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a3372be-37e4-578a-8be9-9ad7bc585dbd")}catch{}})();var U1=4;function Xb(e){let t=e.checks.find(a=>a.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,s=Array.isArray(o)?o.flatMap(a=>{if(typeof a!="object"||a===null||Array.isArray(a))return[];let c=a;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:s}}async function z1(e,t){let n=[];for(let r of t){let o;try{o=await F1(j1.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let s;try{s=JSON.parse(i)}catch{continue}let a=sa(s,r.item_id).find(c=>c.receiptId===r.receipt_id);a===void 0||!ku(a)||a.eventTimestamp===void 0||me(a.eventTimestamp,vu)>=0||n.push({...r,original_event_ts:a.eventTimestamp})}return n}async function H1(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Mr(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function q1(e){try{return{status:"fulfilled",value:await Mr(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function B1(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function G1(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Pl(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function V1(e,t){let n=e.dryRun===!0,r=te(process.cwd(),t.path),o=await Ou(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=Xb(o),s=await z1(r,i.coordinates),a=await Et(r),c=await ft(a??process.cwd(),{includeLossless:!0,pmRoot:r});if(c.invalid_evidence_count>0)throw new w(`Merge reconciliation refused ${c.invalid_evidence_count} invalid receipt evidence file(s).`,h.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let l=await H1({candidates:s,options:e,global:t}),d=c.receipts,u=new Map;for(let M of d){let R=u.get(M.item_id)??[];R.push(M),u.set(M.item_id,R)}let f=Object.fromEntries([...u].map(([M,R])=>[M,{merge:{receipts:R.map(Ft)}}])),p=Object.fromEntries([...u].map(([M,R])=>[M,{gitWorkspaceRoot:a,receipts:R}])),m=await qw({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:f,...d.length>0?{mergeReceiptProofById:p}:{}},t),g=new Set(m.streams.map(M=>M.id)),y=[...u.keys()].filter(M=>!g.has(M)),b=await Ql(y,U1,M=>q1({id:M,dryRun:n,options:e,global:t,auditContext:f[M],mergeReceiptProof:p[M]}));B1({receiptOnlyIds:y,results:b,repair:m});let v=await G1({dryRun:n,pendingReceipts:d,repair:m,gitWorkspaceRoot:a}),A=await Yb({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),I=l===0?o:await Ou(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),x=Xb(I),P=A.checks.every(M=>M.status==="ok"),S=n?d.length===0:v===d.length,E=[m.totals.failed===0,P,S,x.count===0,!x.truncated].every(Boolean),$=i.truncated||x.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Q=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",$,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:E?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",$,...s.length>0&&l===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(M=>M!==void 0);return{ok:E,dry_run:n,repair:m,receipts:{pending_before:d.length,reconciled:v,summaries:d.map(Ft),missing_history_references_before:i.count,legacy_disposition_eligible:s.length,legacy_disposition_recorded:l,missing_history_references_after:x.count},validation:A,guidance:Q,generated_at:A.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="925be497-bdd3-527b-9a88-cf9c9f682ab2")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00dc29ff-60e0-5755-b7f1-4f69e438e87f")}catch{}})();export{x_ as ITEM_LATEST_TIMESTAMP_FIELDS,E_ as ITEM_SCALAR_MISSING_VALUE,S_ as ITEM_UNION_COLLECTION_FIELDS,Bl as MERGE_DRIVER_ARTIFACT_VALUES,Yl as PM_GITATTRIBUTES_END,Co as PM_GITATTRIBUTES_START,Ds as PM_GITATTRIBUTES_V2_END,Kn as PM_GITATTRIBUTES_V2_START,Zl as auditMergeAttributeFence,Oo as auditMergeDriverConfiguration,Ls as buildMergeAttributePatterns,Ne as encodeItemScalarDecisionValue,Et as findGitWorkspaceRoot,vt as hashItemScalarDecisionValue,ft as inspectMergeReceiptEvidence,fR as installMergeFence,Tr as isItemScalarMissingValue,q_ as listMergeReceipts,Pl as markMergeReceiptReconciled,xl as mergeHistoryStreams,Al as mergeItemDocuments,Il as mergeJsonDocuments,Tl as mergeRelationshipEventStreams,_g as refreshMergeAttributeFenceIfInstalled,fg as resolveMergeInstallContext,Ms as resolveProjectMergeTypeFolders,tR as runMergeDriver,uR as runMergeInstall,FC as runMergeReceiptEvidenceReport,$C as runMergeReceiptReport,V1 as runMergeReconcile,Ft as summarizeMergeReceipt};
|
|
113
120
|
//# sourceMappingURL=sdk-merge.js.map
|