@unbrained/pm-cli 2026.8.24 → 2026.8.25
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 +13 -0
- package/dist/cli-bundle/bundle-manifest.json +152 -152
- package/dist/cli-bundle/chunks/{chunk-ZAVCS2GH.js → chunk-244MI4GS.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-NXBFO63A.js → chunk-2F3LUFMW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DJNJBWAQ.js → chunk-5I5RWIJC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X7WWQDYQ.js → chunk-65MHLHAA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-6C7GIMIL.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-IW72J5FW.js → chunk-OWHNAR2B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TEQDR5KI.js → chunk-QKGMHGEI.js} +62 -62
- package/dist/cli-bundle/chunks/{chunk-L22NP5MA.js → chunk-QLUORNIB.js} +86 -86
- package/dist/cli-bundle/chunks/{chunk-AGUL3HUT.js → chunk-T2ENPRXF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-I5Q7QSZX.js → chunk-TPQIBSL2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YQMYF3YD.js +35 -0
- package/dist/cli-bundle/chunks/{register-list-query-37A4P6O4.js → register-list-query-XVN2ZLI7.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-TBJDHYIT.js → register-mutation-QCKAEGIJ.js} +3 -3
- package/dist/cli-bundle/chunks/{register-operations-WRZNEBUM.js → register-operations-SDEAXE7E.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-H4PDLACD.js → register-setup-LXVBRCJ3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CWCN5RLO.js → chunk-2UIWOP3O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-42S3GGZ7.js +50 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BFA6KKCI.js → chunk-7I23XGWO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6Z24ZMU3.js → chunk-7YCDTCBC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O4ZXNJMT.js → chunk-A644DUFQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4WP7LNE3.js → chunk-GQR3WH3F.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RASVBJX5.js → chunk-H5JZEIQV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IBZZZGK3.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-LMKG3DFE.js +5 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6MUTDXMP.js → chunk-N7W67YIG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IMWTYKII.js → chunk-NOOZGIXP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WZLSSGEU.js → chunk-OHIHZ7HS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ONYQCALA.js +19 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QBP5FSBX.js → chunk-OVJL6NZE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RAFKLNZX.js +16 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GJR6YEMR.js → chunk-VXWATRFL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IZNRRCU3.js → chunk-XUQPEKRN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MNPECIRL.js → chunk-YO3ZF3FI.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +41 -41
- 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 +32 -33
- 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 +5 -5
- package/dist/core/diagnostics/remediation.js +17 -2
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +10 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +20 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +49 -25
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +26 -2
- package/dist/sdk/governance/health.js +98 -11
- package/dist/sdk/governance/validate.js +15 -9
- package/dist/sdk/history-repair.d.ts +24 -0
- package/dist/sdk/history-repair.js +145 -4
- package/dist/sdk/merge/driver.js +25 -4
- package/dist/sdk/merge/receipt-file-boundary.d.ts +21 -0
- package/dist/sdk/merge/receipt-file-boundary.js +47 -0
- package/dist/sdk/merge/receipts.d.ts +24 -1
- package/dist/sdk/merge/receipts.js +342 -36
- package/dist/sdk/merge/reconcile.js +117 -47
- package/dist/sdk/read-output/continuation.d.ts +15 -2
- package/dist/sdk/read-output/continuation.js +86 -6
- package/dist/sdk/read-output-contracts.d.ts +4 -1
- package/dist/sdk/read-output-contracts.js +9 -6
- package/docs/MERGE_SAFETY.md +34 -5
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +13 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +25 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +7 -3
- package/marketplace.json +2 -2
- package/package.json +1 -1
- 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 +136 -15
- package/dist/cli-bundle/chunks/chunk-MKE6MD2K.js +0 -36
- package/dist/cli-bundle/chunks/chunk-YOLLRCLY.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-FCTT4CZU.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-Q63PSLO4.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QV5UP27O.js +0 -51
- package/dist/cli-bundle/focused-chunks/chunk-RPRLENVA.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-TOFVXBWA.js +0 -19
|
@@ -1,36 +1,35 @@
|
|
|
1
|
-
import ls 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 wn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],ic=2,sc=Object.freeze({migration:"schema",validation:"schema"}),SI=Object.freeze({version:ic,capabilities:[...wn],legacy_aliases:{...sc}}),Zo=["off","warn","enforce"],Qo=["off","warn","enforce"],ei=["none","restricted","strict"];var ti=["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"],fr=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function pr(){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 ac=["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"],Rm=["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",...ac,"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"],ke=Rm;(function(){try{var e=typeof window<"u"?window:typeof 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 ni=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"]}]),ri=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Vt=".agents/pm",mr="settings.json";var Nm=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],Dm=["decisions","events","reminders","milestones","meetings","plans"],II=[...Nm,...Dm],Te={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},oi={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}},ii=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],kt={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 cc(e){return e?[...e]:void 0}var ne={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:[...ii],lifecycle_closure_like_blocked_reason_patterns:[...kt.blocked_reason],lifecycle_closure_like_resolution_patterns:[...kt.resolution],lifecycle_closure_like_actual_result_patterns:[...kt.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...oi.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:ni.map(e=>({...e,aliases:cc(e.aliases),roles:cc(e.roles)})),fields:[],workflow:{...ri},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:pr()},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:""}}},si={metadata:{},body:""},h={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},OI=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 F_}from"@toon-format/toon";import{isDeepStrictEqual as Lc}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 ai=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],lc=ai,Ht=["draft","open","in_progress","blocked","closed","canceled"],_r=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Wt=["string","number","boolean","string_array","array","object"],gr=["create","update","update_many","list","search","calendar","context"],hr=["allow","warn","reject"];var ci=["project","global"];var yr=["low","medium","high","critical"],br=["low","medium","high"];var dc=["minimal","default","strict","custom"];var wr=["daily","weekly","monthly","yearly"],vn=["mon","tue","wed","thu","fri","sat","sun"];function li(e){return vn.indexOf(e)}var uc=["draft","research","review","approved","executing","paused","completed","superseded"],vr=["pending","in_progress","completed","blocked","skipped","superseded"],fc=["codex","claude-code","cursor","generic"],pc=["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 y=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 Pm 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 Lm(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 Mm(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Er(o))}return n}function Er(e){let t=Lm(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Er(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Er(r)}return Mm(e)}function D(e){return JSON.stringify(Er(e))}function mc(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 Fm(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function $m(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function jm(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(!mc(o,n,r,Se))return!1;return!0}function Um(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(!mc([o,i],n,r,([a,c],[l,d])=>Se(a,l)&&Se(c,d)))return!1;return!0}function zm(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)=>Se(n,t[r]))}function qm(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]||!Se(e[i],t[i]))return!1}return!0}var Bm=[Fm,$m,jm,Um,zm];function Se(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 Bm){let r=n(e,t);if(r!==void 0)return r}return qm(e,t)}function Re(e){return Pm.createHash("sha256").update(e,"utf8").digest("hex")}function ot(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 Kt(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 Gm}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 Vm=new Gm;function _c(){let e=Vm.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 Hm=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function z(){return _c()??new Date().toISOString()}function Ne(e){return Number.isFinite(Date.parse(e))}function hc(e){let t=Hm.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,l]=t,[d,u,f,m,_,g]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=Km(d,u-1)&&m<=23&&_<=59&&g<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var Wm=1e4,kr=new Map;function gc(e){let t=kr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return kr.size>=Wm&&Kt(kr),kr.set(e,n),n}function ue(e,t){let n=gc(e),r=gc(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function Km(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import yc from"node:path";import*as ee from"node:fs/promises";import Tr from"node:path";import Ym 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 Xm=[10,25,50,100];async function it(e){await ee.mkdir(e,{recursive:!0})}async function q(e){try{return await ee.access(e),!0}catch{return!1}}function di(e){return te(e)||Tt(e,"ENOTDIR")}function te(e){return Tt(e,"ENOENT")}async function X(e){try{return await ee.readFile(e,"utf8")}catch(t){if(di(t))return null;throw t}}async function F(e,t){let n=Tr.dirname(e);await it(n);let r=Tr.join(n,`.${Tr.basename(e)}.${process.pid}.${Date.now()}.${Ym.randomBytes(4).toString("hex")}.tmp`);await ee.writeFile(r,t,"utf8");try{await ee.rename(r,e)}catch(o){if(process.platform==="win32"&&(Tt(o,"EPERM")||Tt(o,"EBUSY"))){let i=o;for(let s of Xm){await new Promise(a=>setTimeout(a,s));try{await ee.rename(r,e);return}catch(a){if(i=a,!Tt(a,"EPERM")&&!Tt(a,"EBUSY"))break}}try{await ee.unlink(r)}catch{}throw i}if(Tt(o,"EXDEV")){try{await ee.copyFile(r,e)}finally{try{await ee.unlink(r)}catch{}}return}try{await ee.unlink(r)}catch{}throw o}}async function Yt(e,t){let n=Tr.dirname(e);await it(n);let r=await ee.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
-
`,"utf8")}finally{await r.close()}}function
|
|
3
|
-
`}function g_(){return{definitions:[]}}function h_(){return{statuses:pi}}function y_(){return{fields:[]}}function b_(){return{workflow:vc}}function w_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function v_(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 E_(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 k_(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 T_(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 S_(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 ge(e,t,n){let r=t?.trim()||n;return yc.isAbsolute(r)?r:yc.join(e,r)}async function Ac(e,t){let n=st(t),r=[{path:ge(e,n.files.types,fe.types),seed:g_()},{path:ge(e,n.files.statuses,fe.statuses),seed:h_()},{path:ge(e,n.files.fields,fe.fields),seed:y_()},{path:ge(e,n.files.workflows,fe.workflows),seed:b_()}],o=[];for(let i of r)await q(i.path)||(await F(i.path,__(i.seed)),o.push(i.path));return{created_paths:o}}async function xc(e,t){let n=st(t),r=[],o=ge(e,n.files.types,fe.types),i=ge(e,n.files.statuses,fe.statuses),s=ge(e,n.files.fields,fe.fields),a=ge(e,n.files.workflows,fe.workflows),c,l,d,u,f,m=async(C,O)=>{let A=await X(C);if(A!==null)return w_(A,O,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=v_(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let g=await m(i,"runtime_schema_statuses_invalid_json");g!==void 0&&(l=E_(g),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await m(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=k_(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let E=await m(a,"runtime_schema_workflows_invalid_json");return E!==void 0&&(u=T_(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=S_(E)),{schema:st({...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 ui(e,t,n){let r=e.filter(i=>i.roles.includes(t));if(r.length>0)return r[0].id;let o=n.map(i=>De(i)).filter(i=>typeof i=="string");for(let i of o)if(e.some(s=>s.id===i))return i;return e[0]?.id}function kn(e){let t=st(e),n=t.statuses.map((g,b)=>fi(g,b)).filter(g=>g!==null),r=new Map,o=new Map;for(let g of n){o.set(g.id,g),r.set(g.id,g.id),r.set(g.id.replaceAll("_","-"),g.id),r.set(g.id.replaceAll("_"," "),g.id);for(let b of g.aliases)r.set(b,g.id),r.set(b.replaceAll("_","-"),g.id),r.set(b.replaceAll("_"," "),g.id)}let i=new Set,s=new Set,a=new Set,c=new Set,l=new Set,d=new Set;for(let g of n){let b=new Set(g.roles);(b.has("terminal")||b.has("terminal_done")||b.has("terminal_canceled"))&&i.add(g.id),b.has("terminal_done")&&s.add(g.id),b.has("terminal_canceled")&&a.add(g.id),b.has("active")&&c.add(g.id),b.has("blocked")&&l.add(g.id),b.has("draft")&&d.add(g.id)}let u=t.workflow,f=De(u.open_status)??ui(n,"default_open",["open","in_progress",Ht[0]]),m=De(u.close_status)??ui(n,"default_close",["closed","done","complete"]),_=De(u.canceled_status)??ui(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:i,terminal_done_statuses:s,terminal_canceled_statuses:a,active_statuses:c,blocked_statuses:l,draft_statuses:d,open_status:f,close_status:m,canceled_status:_}}function Cr(e,t){let n=ze(e);if(n)return t.alias_to_id.get(n)}function mi(e){let t=st(e),n=new Map,r=t.fields.map(c=>Sc(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 _i(e,t){let n=Cr(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 A_=16;function Oc(e){return Array.isArray(e)?e.flatMap(t=>Oc(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 Cc(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 y(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Ic(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 y(`${t} must be a number`,h.USAGE);return r}function x_(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 y(`${t} must be valid JSON ${n}`,h.USAGE)}function C_(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 I_(e,t,n){if(t.const!==void 0&&D(e)!==D(t.const))return`${n} must equal ${D(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>D(r)===D(e)))return`${n} must be one of ${t.enum.map(r=>D(r)).join("|")}`;if(!C_(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"&&!hc(e))return`${n} must be an RFC 3339 date-time`}}function O_(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=Ir(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function R_(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=Ir(s,a,`${n}.${i}`,r+1);if(c)return c}}function Ir(e,t,n,r=0){if(r>A_)return`${n} value schema exceeds maximum depth`;let o=I_(e,t,n);if(o)return o;let i=O_(e,t,n,r);if(i)return i;let s=R_(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Ir(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 St(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Ir(t,e.value_schema,n);if(r)throw new y(r,h.USAGE);return t}function Or(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:St(e,x_(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=Oc(t);return e.type==="number"?St(e,i.map(s=>Ic(s,r)),r):e.type==="boolean"?St(e,i.map(s=>Cc(s,r)),r):St(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?St(e,Ic(o,r),r):e.type==="boolean"?St(e,Cc(o,r),r):St(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 Xt=1,Rr=1;function Rc(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=Xt?t:Xt}function Nc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=Xt))return e}function N_(e,t=Rr){return e<t?"outdated":e>t?"ahead":"current"}function Dc(e,t=Rr){let n=[],r=[];for(let o of e){let i=N_(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 D_={"in-progress":"in_progress",cancelled:"canceled"};function At(e,t){if(t){let o=Cr(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=D_[n]??n;if(Ht.includes(r))return r}import{decode as P_}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 gi(e){return{value:P_(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 L_=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function M_(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(L_);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Pe(e){return M_(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 Tn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function de(e){return Tn(e)??void 0}function We(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Pc(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]="65a90a42-eecb-57d3-9f78-3a5f1bc3abd3")}catch{}})();var wi=new Set(["schema","tracker","auto"]),$c=new Set(["source","isolated","snapshot"]),$_=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),j_=new Set(["passed","failed","stopped","canceled"]),U_=new Set(vr);function Qt(e){return e.replaceAll("\\","/")}function jc(e){for(let t of e)if(t!==0)return t;return 0}function Dr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Uc=["id","title","description","created_at","updated_at"],z_=new Set(ke);function zc(e){if(e?.schema)return{statusRegistry:kn(e.schema),fieldRegistry:mi(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function q_(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function at(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new y(`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 xn(e,t){throw new y(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 qc(e){let t=new Set(z_);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function x(e,t){e||at(t)}function Cn(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&at(t),e}function hi(e,t){let n=e[t];x(typeof n=="string",`${t} must be a string`),x(Ne(n),`${t} must be a valid ISO timestamp`)}function Mc(e,t,n){let r=e[t];r!==void 0&&x(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function vi(e,t,n){let r=e[t];r!==void 0&&(x(typeof r=="string",`${n} must be a string`),x(Ne(r),`${n} must be a valid ISO timestamp`))}function B_(e){if(e!==void 0){x(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){x(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();x(vn.includes(n),`event.recurrence.by_weekday entries must be one of: ${vn.join(", ")}`)}}}function G_(e){if(e!==void 0){x(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)x(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function V_(e){if(e!==void 0){x(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)x(typeof t=="string","event.recurrence.exdates entries must be strings"),x(Ne(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function H_(e){let t=Cn(e,"event.recurrence must be an object");x(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();x(wr.includes(n),`event.recurrence.freq must be one of: ${wr.join(", ")}`),Mc(t,"interval","event.recurrence.interval"),Mc(t,"count","event.recurrence.count"),vi(t,"until","event.recurrence.until"),B_(t.by_weekday),G_(t.by_month_day),V_(t.exdates)}function W_(e){for(let r of Uc)x(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;x(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&x(typeof n=="number"&&Number.isInteger(n)&&n>=Xt,`pm_format_version must be an integer >= ${Xt}`),t}function K_(e,t){let n=e.status;x(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=At(n,r),i=r?r.definitions.map(s=>s.id):[...Ht];x(o!==void 0,`status must be one of: ${i.join(", ")}`)}function Y_(e){let t=e.priority;x(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;x(Array.isArray(n),"tags must be an array");for(let r of n)x(typeof r=="string","tags entries must be strings")}function X_(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){x(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"||br.includes(n);x(r,`confidence string value must be one of: ${[...br,"med"].join(", ")}`);return}x(!1,"confidence must be a number or string")}}function J_(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&at("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||yr.includes(n);x(r,`severity value must be one of: ${[...yr,"med"].join(", ")}`)}function Z_(e){e.regression!==void 0&&typeof e.regression!="boolean"&&at("regression must be a boolean")}function Q_(e){let t=e.reminders;if(t!==void 0){x(Array.isArray(t),"reminders must be an array");for(let n of t){let r=Cn(n,"reminders entries must be objects");x(typeof r.at=="string","reminder.at must be a string"),x(Ne(r.at),"reminder.at must be a valid ISO timestamp"),x(typeof r.text=="string","reminder.text must be a string"),x(r.text.trim().length>0,"reminder.text must not be empty")}}}function eg(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(x(typeof e[t]=="string",`event.${t} must be a string`),x(e[t].trim().length>0,`event.${t} must not be empty`))}function tg(e){e.recurrence!==void 0&&(H_(e.recurrence),e.recurrence.until!==void 0&&x(ue(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function ng(e){let t=Cn(e,"events entries must be objects");x(typeof t.start_at=="string","event.start_at must be a string"),x(Ne(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(x(typeof t.end_at=="string","event.end_at must be a string"),x(Ne(t.end_at),"event.end_at must be a valid ISO timestamp"),x(ue(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),eg(t),t.all_day!==void 0&&x(typeof t.all_day=="boolean","event.all_day must be a boolean"),tg(t)}function rg(e){let t=e.events;if(t!==void 0){x(Array.isArray(t),"events must be an array");for(let n of t)ng(n)}}function og(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&x(typeof n=="string",`${t} must be a string`)}}function ig(e){let t=e.type_options;if(t===void 0)return;let n=Cn(t,"type_options must be an object");for(let[r,o]of Object.entries(n))x(r.trim().length>0,"type_options keys must be non-empty"),x(typeof o=="string","type_options values must be strings"),x(o.trim().length>0,"type_options values must be non-empty strings")}function sg(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){q_(r,t)&&at(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=Or(r,o,`metadata field "${r.metadata_key}"`)}catch(i){at(String(i?.message).replace(/^Invalid\s+/u,""))}}}function ag(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=qc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?at(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ei(e,t){let n=Cn(e,"item metadata must be an object"),r=W_(n);K_(n,t),Y_(n),X_(n),J_(n),Z_(n),hi(n,"created_at"),hi(n,"updated_at"),n.deadline!==void 0&&hi(n,"deadline"),Q_(n),rg(n),vi(n,"closed_at","closed_at"),vi(n,"completed_at","completed_at"),og(n),ig(n),sg(n,r,t),ag(n,t)}function cg(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim().toLowerCase(),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=ue(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 yi(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=ue(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 lg(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=ue(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function dg(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!wr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>vn.includes(s)))).sort((s,a)=>li(s)-li(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=>Ne(s)))).sort((s,a)=>ue(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 ug(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(fg).sort(pg)}function fg(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:dg(e.recurrence)};return Dr(t),t}function pg(e,t){return jc([ue(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 mg(e){if(!(!e||e.length===0))return e.map(t=>({path:Qt(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function _g(e){if(!e||e.length===0)return;let t=e.map(bg).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)=>jc([ue(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 Jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function gg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function bi(e){return typeof e=="string"?e:""}function hg(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 Nr(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function yg(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:Nr(n.requested_pm_context_mode,wi),pm_context_mode:Nr(n.pm_context_mode,wi),workspace_context_mode:Nr(n.workspace_context_mode,$c),trust_reason:Nr(n.trust_reason,$_)}));return t.length>0?t:void 0}function bg(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=j_.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:bi(e.started_at),finished_at:bi(e.finished_at),recorded_at:bi(e.recorded_at),attempt:gg(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:Jt(e.passed)??0,failed:Jt(e.failed)??0,skipped:Jt(e.skipped)??0,items:Jt(e.items),linked_tests:Jt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:hg(e.measurements),executions:yg(e.executions)};return Dr(o),o}function wg(e){if(!(!Array.isArray(e)||e.length===0))return e.map(Sg)}function Sn(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 Ti(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Si(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Fc(e){if(!Ti(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Si(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function vg(e){if(!Ti(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Si(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Eg(e){let t=e?.trim().toLowerCase();if(!(!t||!wi.has(t)))return t}function kg(e){let t=e?.trim().toLowerCase();if(!(!t||!$c.has(t)))return t}function Tg(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ti(e))return{provenance_invalid:!0};let n=S(e.author),r=S(e.created_at),o=e.source_kind;return!n||!r||!Ne(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:S(e.source_ref)}}}function Sg(e){let t={command:e.command?.trim()||void 0,path:e.path?Qt(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:Eg(e.pm_context_mode),workspace_context_mode:kg(e.workspace_context_mode),...Tg(e.provenance,e.provenance_invalid),env_set:Fc(e.env_set),env_clear:Sn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:Sn(e.assert_stdout_contains),assert_stdout_regex:Sn(e.assert_stdout_regex),assert_stderr_contains:Sn(e.assert_stderr_contains),assert_stderr_regex:Sn(e.assert_stderr_regex),assert_stdout_min_lines:Jt(e.assert_stdout_min_lines),assert_json_field_equals:Fc(e.assert_json_field_equals),assert_json_field_gte:vg(e.assert_json_field_gte),note:e.note?.trim()||void 0};return Dr(t),t}function Ag(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Qt(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 S(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function xg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.id),i=S(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=S(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 Cg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:Qt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Ig(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.command),i=S(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Qt(i));let a=S(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function Og(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:Qt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Rg(e){if(e===null||typeof e!="object")return;let t=e,n=S(t.id),r=S(t.title),o=S(t.status),i=o&&U_.has(o)?o:void 0,s=Pc(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 Ng(l,t),l}function Ng(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=S(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",xg],["files","files",Cg],["tests","tests",Ig],["docs","docs",Og]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function Dg(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=Rg(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function Pg(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=S(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=S(r.rationale);c&&(a.rationale=c);let l=S(r.evidence);l&&(a.evidence=l);let d=S(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function Lg(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=S(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=S(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function Mg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.text);if(!o)continue;let i={text:o},s=S(r.command);s&&(i.command=s);let a=S(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function Fg(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 Zt(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 _s 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 wn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],pc=2,mc=Object.freeze({migration:"schema",validation:"schema"}),wO=Object.freeze({version:pc,capabilities:[...wn],legacy_aliases:{...mc}}),oi=["off","warn","enforce"],ii=["off","warn","enforce"],si=["none","restricted","strict"];var ai=["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"],br=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function wr(){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 _c=["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"],Km=["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",..._c,"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"],Te=Km;(function(){try{var e=typeof window<"u"?window:typeof 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 ci=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"]}]),li=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Ht=".agents/pm",vr="settings.json";var Ym=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],Xm=["decisions","events","reminders","milestones","meetings","plans"],TO=[...Ym,...Xm],Se={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},di={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}},ui=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],St={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 gc(e){return e?[...e]:void 0}var re={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:[...ui],lifecycle_closure_like_blocked_reason_patterns:[...St.blocked_reason],lifecycle_closure_like_resolution_patterns:[...St.resolution],lifecycle_closure_like_actual_result_patterns:[...St.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...di.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:ci.map(e=>({...e,aliases:gc(e.aliases),roles:gc(e.roles)})),fields:[],workflow:{...li},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:wr()},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:""}}},fi={metadata:{},body:""},h={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},SO=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 eg}from"@toon-format/toon";import{isDeepStrictEqual as qc}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 pi=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],hc=pi,Wt=["draft","open","in_progress","blocked","closed","canceled"],Er=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Kt=["string","number","boolean","string_array","array","object"],kr=["create","update","update_many","list","search","calendar","context"],Tr=["allow","warn","reject"];var mi=["project","global"];var Sr=["low","medium","high","critical"],Ar=["low","medium","high"];var yc=["minimal","default","strict","custom"];var xr=["daily","weekly","monthly","yearly"],vn=["mon","tue","wed","thu","fri","sat","sun"];function _i(e){return vn.indexOf(e)}var bc=["draft","research","review","approved","executing","paused","completed","superseded"],Cr=["pending","in_progress","completed","blocked","skipped","superseded"],wc=["codex","claude-code","cursor","generic"],vc=["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 y=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 Jm 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 Zm(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 Qm(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Ir(o))}return n}function Ir(e){let t=Zm(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Ir(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Ir(r)}return Qm(e)}function O(e){return JSON.stringify(Ir(e))}function Ec(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_(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function t_(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function n_(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(!Ec(o,n,r,Ae))return!1;return!0}function r_(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(!Ec([o,i],n,r,([a,c],[l,d])=>Ae(a,l)&&Ae(c,d)))return!1;return!0}function o_(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)=>Ae(n,t[r]))}function i_(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]||!Ae(e[i],t[i]))return!1}return!0}var s_=[e_,t_,n_,r_,o_];function Ae(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 s_){let r=n(e,t);if(r!==void 0)return r}return i_(e,t)}function ce(e){return Jm.createHash("sha256").update(e,"utf8").digest("hex")}function it(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 Yt(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 a_}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 c_=new a_;function kc(){let e=c_.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 l_=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function q(){return kc()??new Date().toISOString()}function De(e){return Number.isFinite(Date.parse(e))}function En(e){let t=l_.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,_,g]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=u_(d,u-1)&&p<=23&&_<=59&&g<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var d_=1e4,Or=new Map;function Tc(e){let t=Or.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Or.size>=d_&&Yt(Or),Or.set(e,n),n}function pe(e,t){let n=Tc(e),r=Tc(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function u_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import Sc from"node:path";import*as ee from"node:fs/promises";import Rr from"node:path";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]="23fc5fcb-5c80-57ab-8d91-8d15ee35ab53")}catch{}})();var p_=[10,25,50,100];async function st(e){await ee.mkdir(e,{recursive:!0})}async function B(e){try{return await ee.access(e),!0}catch{return!1}}function kn(e){return te(e)||At(e,"ENOTDIR")}function te(e){return At(e,"ENOENT")}async function X(e){try{return await ee.readFile(e,"utf8")}catch(t){if(kn(t))return null;throw t}}async function $(e,t){let n=Rr.dirname(e);await st(n);let r=Rr.join(n,`.${Rr.basename(e)}.${process.pid}.${Date.now()}.${f_.randomBytes(4).toString("hex")}.tmp`);await ee.writeFile(r,t,"utf8");try{await ee.rename(r,e)}catch(o){if(process.platform==="win32"&&(At(o,"EPERM")||At(o,"EBUSY"))){let i=o;for(let s of p_){await new Promise(a=>setTimeout(a,s));try{await ee.rename(r,e);return}catch(a){if(i=a,!At(a,"EPERM")&&!At(a,"EBUSY"))break}}try{await ee.unlink(r)}catch{}throw i}if(At(o,"EXDEV")){try{await ee.copyFile(r,e)}finally{try{await ee.unlink(r)}catch{}}return}try{await ee.unlink(r)}catch{}throw o}}async function Xt(e,t){let n=Rr.dirname(e);await st(n);let r=await ee.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
+
`,"utf8")}finally{await r.close()}}function At(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 m_=2e3,Nr=new Map;function qe(e){if(typeof e!="string")return"";let t=Nr.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Nr.size>=m_&&Yt(Nr),Nr.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]="88b9179f-569e-5cd6-b67c-c27431961554")}catch{}})();var me=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Cc=li,yi=ci,__=["create","update"],g_=new Set(Er),h_=new Set(Kt),y_=new Set(kr),b_=new Set(Tr),w_=new Set(["string","number","boolean","array","object"]),v_=16;function Ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var E_=[e=>e.type===void 0||typeof e.type=="string"&&w_.has(e.type),e=>!Object.hasOwn(e,"const")||Pr(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Pr(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||Ic(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Pr(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=>Pr(r,t)):Object.values(e).every(r=>Pr(r,t));return t.delete(e),n}function Dr(e,t=0,n=new Set){if(!Ic(e)||t>v_||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(!E_.every(k=>k(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([k,I])=>[k,Dr(I,t+1,n)])),g=c===void 0?void 0:Dr(c,t+1,n),b=s===void 0?void 0:s.map(k=>Dr(k,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[g],...b??[]].some(k=>k===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:_,required:l===void 0?void 0:[...new Set(l)],additional_properties:p,items:g,one_of:b}).filter(([,k])=>k!==void 0))}function Tn(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 Pe(e){if(typeof e!="string"||e.length===0)return;let t=qe(e);return t.length>0?t:void 0}function k_(e){return e.startsWith("--")?e.slice(2):e}function Ac(e){return typeof e=="string"?k_(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Oc(e){return e.replaceAll("_","-")}function hi(e,t){let n=Pe(e.id);if(!n)return null;let r=[...new Set(Tn(e.aliases).map(qe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=Tn(e.roles).filter(a=>g_.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 T_(e){return{draft_status:Pe(e?.draft_status),open_status:Pe(e?.open_status),in_progress_status:Pe(e?.in_progress_status),blocked_status:Pe(e?.blocked_status),close_status:Pe(e?.close_status),canceled_status:Pe(e?.canceled_status)}}function Rc(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=qe(t[0]),r=qe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function S_(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)Rc(n,r);return{typeKey:t.toLowerCase(),record:n}}function A_(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=S_(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)Rc(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 Nc(e){let t=qe(e.key??"");if(!t)return null;let n=qe(e.metadata_key??e.front_matter_key??t),r=Ac(e.cli_flag??Oc(t));if(!r)return null;let o=Tn(e.cli_aliases).map(u=>Ac(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=h_.has(i)?i:"string",a=(()=>{let u=Tn(e.commands).filter(f=>y_.has(f));return u.length>0?u:[...__]})(),c=e.description?.trim(),l=Tn(e.required_types),d=e.value_schema===void 0?void 0:Dr(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 x_(e){let t=new Map;for(let[r,o]of e.entries()){let i=hi(o,r);i&&t.set(i.id,i)}let n=xc([...t.values()]);return n.length>0?n:xc(yi.map((r,o)=>hi(r,o)).filter(r=>r!==null))}function xc(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function C_(e){let t=new Map;for(let n of e??[]){let r=Nc(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function I_(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 O_(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Oc(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 R_(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return b_.has(t)?t:"allow"}function at(e){let t={...me,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:yi,r=x_(n),o=C_(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(I_),fields:o.map(O_),workflow:{...Cc,...T_(e?.workflow)},type_workflows:A_(e?.type_workflows),unknown_field_policy:R_(e?.unknown_field_policy)}}function N_(e){return`${JSON.stringify(e,null,2)}
|
|
3
|
+
`}function D_(){return{definitions:[]}}function P_(){return{statuses:yi}}function L_(){return{fields:[]}}function M_(){return{workflow:Cc}}function F_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function $_(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 j_(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 U_(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 z_(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 q_(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 ye(e,t,n){let r=t?.trim()||n;return Sc.isAbsolute(r)?r:Sc.join(e,r)}async function Dc(e,t){let n=at(t),r=[{path:ye(e,n.files.types,me.types),seed:D_()},{path:ye(e,n.files.statuses,me.statuses),seed:P_()},{path:ye(e,n.files.fields,me.fields),seed:L_()},{path:ye(e,n.files.workflows,me.workflows),seed:M_()}],o=[];for(let i of r)await B(i.path)||(await $(i.path,N_(i.seed)),o.push(i.path));return{created_paths:o}}async function Pc(e,t){let n=at(t),r=[],o=ye(e,n.files.types,me.types),i=ye(e,n.files.statuses,me.statuses),s=ye(e,n.files.fields,me.fields),a=ye(e,n.files.workflows,me.workflows),c,l,d,u,f,p=async(I,x)=>{let v=await X(I);if(v!==null)return F_(v,x,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=$_(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let g=await p(i,"runtime_schema_statuses_invalid_json");g!==void 0&&(l=j_(g),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await p(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=U_(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let T=await p(a,"runtime_schema_workflows_invalid_json");return T!==void 0&&(u=z_(T),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=q_(T)),{schema:at({...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 gi(e,t,n){let r=e.filter(i=>i.roles.includes(t));if(r.length>0)return r[0].id;let o=n.map(i=>Pe(i)).filter(i=>typeof i=="string");for(let i of o)if(e.some(s=>s.id===i))return i;return e[0]?.id}function Sn(e){let t=at(e),n=t.statuses.map((g,b)=>hi(g,b)).filter(g=>g!==null),r=new Map,o=new Map;for(let g of n){o.set(g.id,g),r.set(g.id,g.id),r.set(g.id.replaceAll("_","-"),g.id),r.set(g.id.replaceAll("_"," "),g.id);for(let b of g.aliases)r.set(b,g.id),r.set(b.replaceAll("_","-"),g.id),r.set(b.replaceAll("_"," "),g.id)}let i=new Set,s=new Set,a=new Set,c=new Set,l=new Set,d=new Set;for(let g of n){let b=new Set(g.roles);(b.has("terminal")||b.has("terminal_done")||b.has("terminal_canceled"))&&i.add(g.id),b.has("terminal_done")&&s.add(g.id),b.has("terminal_canceled")&&a.add(g.id),b.has("active")&&c.add(g.id),b.has("blocked")&&l.add(g.id),b.has("draft")&&d.add(g.id)}let u=t.workflow,f=Pe(u.open_status)??gi(n,"default_open",["open","in_progress",Wt[0]]),p=Pe(u.close_status)??gi(n,"default_close",["closed","done","complete"]),_=Pe(u.canceled_status)??gi(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:i,terminal_done_statuses:s,terminal_canceled_statuses:a,active_statuses:c,blocked_statuses:l,draft_statuses:d,open_status:f,close_status:p,canceled_status:_}}function Lr(e,t){let n=qe(e);if(n)return t.alias_to_id.get(n)}function bi(e){let t=at(e),n=new Map,r=t.fields.map(c=>Nc(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 wi(e,t){let n=Lr(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 B_=16;function Fc(e){return Array.isArray(e)?e.flatMap(t=>Fc(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 Lc(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 y(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Mc(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 y(`${t} must be a number`,h.USAGE);return r}function G_(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 y(`${t} must be valid JSON ${n}`,h.USAGE)}function V_(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 H_(e,t,n){if(t.const!==void 0&&O(e)!==O(t.const))return`${n} must equal ${O(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>O(r)===O(e)))return`${n} must be one of ${t.enum.map(r=>O(r)).join("|")}`;if(!V_(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"&&!En(e))return`${n} must be an RFC 3339 date-time`}}function W_(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=Mr(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function K_(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=Mr(s,a,`${n}.${i}`,r+1);if(c)return c}}function Mr(e,t,n,r=0){if(r>B_)return`${n} value schema exceeds maximum depth`;let o=H_(e,t,n);if(o)return o;let i=W_(e,t,n,r);if(i)return i;let s=K_(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Mr(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 xt(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Mr(t,e.value_schema,n);if(r)throw new y(r,h.USAGE);return t}function Fr(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:xt(e,G_(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=Fc(t);return e.type==="number"?xt(e,i.map(s=>Mc(s,r)),r):e.type==="boolean"?xt(e,i.map(s=>Lc(s,r)),r):xt(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?xt(e,Mc(o,r),r):e.type==="boolean"?xt(e,Lc(o,r),r):xt(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 Jt=1,$r=1;function $c(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=Jt?t:Jt}function jc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=Jt))return e}function Y_(e,t=$r){return e<t?"outdated":e>t?"ahead":"current"}function Uc(e,t=$r){let n=[],r=[];for(let o of e){let i=Y_(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 X_={"in-progress":"in_progress",cancelled:"canceled"};function Ct(e,t){if(t){let o=Lr(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=X_[n]??n;if(Wt.includes(r))return r}import{decode as J_}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 vi(e){return{value:J_(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 Z_=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function Q_(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(Z_);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Le(e){return Q_(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 An(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ue(e){return An(e)??void 0}function Ke(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function zc(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]="65a90a42-eecb-57d3-9f78-3a5f1bc3abd3")}catch{}})();var Si=new Set(["schema","tracker","auto"]),Vc=new Set(["source","isolated","snapshot"]),tg=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),ng=new Set(["passed","failed","stopped","canceled"]),rg=new Set(Cr);function en(e){return e.replaceAll("\\","/")}function Hc(e){for(let t of e)if(t!==0)return t;return 0}function Ur(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Wc=["id","title","description","created_at","updated_at"],og=new Set(Te);function Kc(e){if(e?.schema)return{statusRegistry:Sn(e.schema),fieldRegistry:bi(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function ig(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function ct(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new y(`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 In(e,t){throw new y(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 Yc(e){let t=new Set(og);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function C(e,t){e||ct(t)}function On(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&ct(t),e}function Ei(e,t){let n=e[t];C(typeof n=="string",`${t} must be a string`),C(De(n),`${t} must be a valid ISO timestamp`)}function Bc(e,t,n){let r=e[t];r!==void 0&&C(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Ai(e,t,n){let r=e[t];r!==void 0&&(C(typeof r=="string",`${n} must be a string`),C(De(r),`${n} must be a valid ISO timestamp`))}function sg(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){C(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();C(vn.includes(n),`event.recurrence.by_weekday entries must be one of: ${vn.join(", ")}`)}}}function ag(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)C(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function cg(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)C(typeof t=="string","event.recurrence.exdates entries must be strings"),C(De(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function lg(e){let t=On(e,"event.recurrence must be an object");C(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();C(xr.includes(n),`event.recurrence.freq must be one of: ${xr.join(", ")}`),Bc(t,"interval","event.recurrence.interval"),Bc(t,"count","event.recurrence.count"),Ai(t,"until","event.recurrence.until"),sg(t.by_weekday),ag(t.by_month_day),cg(t.exdates)}function dg(e){for(let r of Wc)C(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;C(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&C(typeof n=="number"&&Number.isInteger(n)&&n>=Jt,`pm_format_version must be an integer >= ${Jt}`),t}function ug(e,t){let n=e.status;C(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Ct(n,r),i=r?r.definitions.map(s=>s.id):[...Wt];C(o!==void 0,`status must be one of: ${i.join(", ")}`)}function fg(e){let t=e.priority;C(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;C(Array.isArray(n),"tags must be an array");for(let r of n)C(typeof r=="string","tags entries must be strings")}function pg(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){C(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"||Ar.includes(n);C(r,`confidence string value must be one of: ${[...Ar,"med"].join(", ")}`);return}C(!1,"confidence must be a number or string")}}function mg(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&ct("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Sr.includes(n);C(r,`severity value must be one of: ${[...Sr,"med"].join(", ")}`)}function _g(e){e.regression!==void 0&&typeof e.regression!="boolean"&&ct("regression must be a boolean")}function gg(e){let t=e.reminders;if(t!==void 0){C(Array.isArray(t),"reminders must be an array");for(let n of t){let r=On(n,"reminders entries must be objects");C(typeof r.at=="string","reminder.at must be a string"),C(De(r.at),"reminder.at must be a valid ISO timestamp"),C(typeof r.text=="string","reminder.text must be a string"),C(r.text.trim().length>0,"reminder.text must not be empty")}}}function hg(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(C(typeof e[t]=="string",`event.${t} must be a string`),C(e[t].trim().length>0,`event.${t} must not be empty`))}function yg(e){e.recurrence!==void 0&&(lg(e.recurrence),e.recurrence.until!==void 0&&C(pe(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function bg(e){let t=On(e,"events entries must be objects");C(typeof t.start_at=="string","event.start_at must be a string"),C(De(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(C(typeof t.end_at=="string","event.end_at must be a string"),C(De(t.end_at),"event.end_at must be a valid ISO timestamp"),C(pe(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),hg(t),t.all_day!==void 0&&C(typeof t.all_day=="boolean","event.all_day must be a boolean"),yg(t)}function wg(e){let t=e.events;if(t!==void 0){C(Array.isArray(t),"events must be an array");for(let n of t)bg(n)}}function vg(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&C(typeof n=="string",`${t} must be a string`)}}function Eg(e){let t=e.type_options;if(t===void 0)return;let n=On(t,"type_options must be an object");for(let[r,o]of Object.entries(n))C(r.trim().length>0,"type_options keys must be non-empty"),C(typeof o=="string","type_options values must be strings"),C(o.trim().length>0,"type_options values must be non-empty strings")}function kg(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){ig(r,t)&&ct(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=Fr(r,o,`metadata field "${r.metadata_key}"`)}catch(i){ct(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Tg(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Yc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?ct(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function xi(e,t){let n=On(e,"item metadata must be an object"),r=dg(n);ug(n,t),fg(n),pg(n),mg(n),_g(n),Ei(n,"created_at"),Ei(n,"updated_at"),n.deadline!==void 0&&Ei(n,"deadline"),gg(n),wg(n),Ai(n,"closed_at","closed_at"),Ai(n,"completed_at","completed_at"),vg(n),Eg(n),kg(n,r,t),Tg(n,t)}function Sg(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim().toLowerCase(),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=pe(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 ki(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=pe(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 Ag(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=pe(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function xg(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!xr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>vn.includes(s)))).sort((s,a)=>_i(s)-_i(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=>De(s)))).sort((s,a)=>pe(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 Cg(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(Ig).sort(Og)}function Ig(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:xg(e.recurrence)};return Ur(t),t}function Og(e,t){return Hc([pe(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 Rg(e){if(!(!e||e.length===0))return e.map(t=>({path:en(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Ng(e){if(!e||e.length===0)return;let t=e.map(Mg).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)=>Hc([pe(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 Zt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Dg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ti(e){return typeof e=="string"?e:""}function Pg(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 jr(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function Lg(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:jr(n.requested_pm_context_mode,Si),pm_context_mode:jr(n.pm_context_mode,Si),workspace_context_mode:jr(n.workspace_context_mode,Vc),trust_reason:jr(n.trust_reason,tg)}));return t.length>0?t:void 0}function Mg(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=ng.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ti(e.started_at),finished_at:Ti(e.finished_at),recorded_at:Ti(e.recorded_at),attempt:Dg(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:Zt(e.passed)??0,failed:Zt(e.failed)??0,skipped:Zt(e.skipped)??0,items:Zt(e.items),linked_tests:Zt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Pg(e.measurements),executions:Lg(e.executions)};return Ur(o),o}function Fg(e){if(!(!Array.isArray(e)||e.length===0))return e.map(qg)}function xn(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 Ii(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Oi(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Gc(e){if(!Ii(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Oi(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function $g(e){if(!Ii(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Oi(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function jg(e){let t=e?.trim().toLowerCase();if(!(!t||!Si.has(t)))return t}function Ug(e){let t=e?.trim().toLowerCase();if(!(!t||!Vc.has(t)))return t}function zg(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ii(e))return{provenance_invalid:!0};let n=A(e.author),r=A(e.created_at),o=e.source_kind;return!n||!r||!De(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:A(e.source_ref)}}}function qg(e){let t={command:e.command?.trim()||void 0,path:e.path?en(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:jg(e.pm_context_mode),workspace_context_mode:Ug(e.workspace_context_mode),...zg(e.provenance,e.provenance_invalid),env_set:Gc(e.env_set),env_clear:xn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:xn(e.assert_stdout_contains),assert_stdout_regex:xn(e.assert_stdout_regex),assert_stderr_contains:xn(e.assert_stderr_contains),assert_stderr_regex:xn(e.assert_stderr_regex),assert_stdout_min_lines:Zt(e.assert_stdout_min_lines),assert_json_field_equals:Gc(e.assert_json_field_equals),assert_json_field_gte:$g(e.assert_json_field_gte),note:e.note?.trim()||void 0};return Ur(t),t}function Bg(e){if(!(!e||e.length===0))return[...e].map(t=>({path:en(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 A(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Gg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=A(r.id),i=A(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=A(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 Vg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=A(r.path);if(!o)continue;let i={path:en(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=A(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Hg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=A(r.command),i=A(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=en(i));let a=A(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function Wg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=A(r.path);if(!o)continue;let i={path:en(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=A(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Kg(e){if(e===null||typeof e!="object")return;let t=e,n=A(t.id),r=A(t.title),o=A(t.status),i=o&&rg.has(o)?o:void 0,s=zc(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 Yg(l,t),l}function Yg(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=A(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",Gg],["files","files",Vg],["tests","tests",Hg],["docs","docs",Wg]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function Xg(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=Kg(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function Jg(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=A(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=A(r.rationale);c&&(a.rationale=c);let l=A(r.evidence);l&&(a.evidence=l);let d=A(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function Zg(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=A(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=A(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function Qg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=A(r.text);if(!o)continue;let i={text:o},s=A(r.command);s&&(i.command=s);let a=A(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function eh(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 Qt(e){let t=0;for(;t<e.length&&e[t]===`
|
|
4
|
+
`;)t+=1;return e.slice(t).trimEnd()}function th(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ar.includes(t))return t}function nh(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Sr.includes(t))return t}function Cn(e){return e||void 0}function rh(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Oi(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function oh(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]=Fr(r,o,`metadata field "${r.metadata_key}"`))}}function ih(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Yc(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&ct(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function Rn(e,t={}){let n=Kc(t),r=Ct(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:jc(e.pm_format_version),source_type:A(e.source_type),type_options:eh(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Sg(e.dependencies),comments:ki(e.comments),notes:ki(e.notes),learnings:ki(e.learnings),files:Rg(e.files),tests:Fg(e.tests),test_runs:Ng(e.test_runs),docs:Bg(e.docs),deadline:Cn(e.deadline),reminders:Ag(e.reminders),events:Cg(e.events),closed_at:Cn(e.closed_at),completed_at:Cn(e.completed_at),assignee:A(e.assignee),claim_principal:A(e.claim_principal),source_owner:A(e.source_owner),author:Cn(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:A(e.definition_of_ready),order:e.order,goal:A(e.goal),objective:A(e.objective),value:A(e.value),impact:A(e.impact),outcome:A(e.outcome),why_now:A(e.why_now),parent:A(e.parent),reviewer:A(e.reviewer),risk:e.risk??void 0,confidence:th(e.confidence),sprint:A(e.sprint),release:A(e.release),blocked_by:A(e.blocked_by),blocked_reason:A(e.blocked_reason),unblock_note:A(e.unblock_note),reporter:A(e.reporter),severity:nh(e.severity),environment:A(e.environment),repro_steps:A(e.repro_steps),resolution:A(e.resolution),expected_result:A(e.expected_result),actual_result:A(e.actual_result),affected_version:A(e.affected_version),fixed_version:A(e.fixed_version),component:A(e.component),regression:e.regression,customer_impact:A(e.customer_impact),close_reason:Cn(e.close_reason),plan_mode:A(e.plan_mode),plan_scope:A(e.plan_scope),plan_harness:A(e.plan_harness),plan_resume_context:A(e.plan_resume_context),plan_steps:Xg(e.plan_steps),plan_decisions:Jg(e.plan_decisions),plan_discoveries:Zg(e.plan_discoveries),plan_validation:Qg(e.plan_validation)};return rh(i,e),oh(i,n),ih(i,n),Ur(i),i}function Xc(e){return it(e,Te)}function sh(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 ah(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=sh(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 ch(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 Ci(e,t){return Rn(e,{...t,onWarning:void 0})}function lh(e,t,n={}){let r=ch(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=ah(r.content);o||(e.trimStart().startsWith("{")&&In("json_markdown","JSON front matter is not valid JSON"),In("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{In("json_markdown","JSON front matter is not valid JSON")}return xi(s,t),{metadata:Ci(s,n),body:Qt(i)}}function dh(e,t,n={}){let r;try{r=vi(e).value}catch{In("toon","TOON item document is not valid TOON")}C(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!Wc.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&In("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return xi(o.front_matter,t),C(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Ci(o.front_matter,n),body:Qt(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return C(i===void 0||typeof i=="string","TOON item document body must be a string"),xi(s,t),{metadata:Ci(s,n),body:Qt(typeof i=="string"?i:"")}}function uh(e,t={}){let n=Rn(e.metadata,t),r=Xc(n),o=JSON.stringify(r,null,2),i=Qt(e.body??"");return i?`${o}
|
|
6
6
|
|
|
7
7
|
${i}
|
|
8
8
|
`:`${o}
|
|
9
|
-
`}function
|
|
10
|
-
`}function qe(e,t={}){let n=Pe(e);if(n)throw new y(`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=zc(t);return r==="toon"?Wg(e,o,t):Hg(e,o,t)}function xt(e,t={}){return(t.format??"toon")==="toon"?Yg(e,t):Kg(e,t)}function he(e,t={}){return{metadata:In(e.metadata,t),body:Zt(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 Xl from"fast-json-patch";import{AsyncLocalStorage as py}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 Pr from"node:fs";import Ct from"node:path";import{fileURLToPath as Xg}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 Jg="@unbrained/pm-cli";function Zg(e){try{return JSON.parse(Pr.readFileSync(e,"utf8")).name===Jg}catch{return!1}}function Qg(e){let t=Pr.existsSync(e)&&Pr.statSync(e).isDirectory()?Ct.resolve(e):Ct.dirname(Ct.resolve(e));for(;;){let n=Ct.join(t,"package.json");if(Pr.existsSync(n)&&Zg(n))return t;let r=Ct.dirname(t);if(r===t)return;t=r}}function en(e,t=[]){let n=Xg(e),r=Qg(n);return r||Ct.resolve(Ct.dirname(n),...t)}import{readFileSync as wh,readdirSync as eR,statSync as vh}from"node:fs";import J from"node:path";import oh 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 ct(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function eh(e){let t=e.key.trim();if(t.length===0)return null;let n=ct(e.aliases),r=e.description?.trim();return{key:t,values:ct(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 th=e=>e,Vc=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function nh(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 rh(e,t){let n=new Map;for(let r of e??[]){let o=nh(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 Gc(e,t){return t?ct(e):void 0}function Ai(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Lr(e,t={}){let n=t.resolvePolicyCommand??th,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=ct(e.aliases),l=(e.options??[]).map(u=>eh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=rh(e.command_option_policies,n);return{name:r,description:Ai(e.description),default_status:Ai(e.default_status),folder:Ai(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Gc(e.required_create_fields,o),required_create_repeatables:Gc(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 ih=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],sh=["dep","comment","note","learning","file","test","doc"],xi=["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"],HO=["title","description","type","status","priority","tags","body",...xi,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],WO=["title","description","body","status","closeReason","priority","type","tags",...xi,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Wc={"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"},KO={...Wc},YO={...Wc},Kc=[["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"]],Yc=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Xc(e){return Object.fromEntries(e)}var XO=Xc([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Kc,["author","--author"],["message","--message"],["dep","--dep"],...Yc]),JO=Xc([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Kc,...Yc,["author","--author"],["message","--message"],["force","--force"]]);function Mr(e){let t=ah(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Jc(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=oh.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 ah(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 ch(e){return Lr(e,{resolvePolicyCommand:Vc})}function On(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function lh(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:On(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:On(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function dh(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 uh(e){if(Array.isArray(e.options))return e.options.map(t=>lh(t)).filter(t=>t!==null)}function fh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>dh(t)).filter(t=>t!==null)}function ph(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:On(t,"aliases"),required_create_fields:On(t,"required_create_fields"),required_create_repeatables:On(t,"required_create_repeatables"),options:uh(t),command_option_policies:fh(t)}}function mh(e,t){return e.required_create_fields?ct(e.required_create_fields):t?.required_create_fields??[]}function _h(e,t){return e.required_create_repeatables?ct(e.required_create_repeatables):t?.required_create_repeatables??[]}function gh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function hh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function yh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=Jc(e.folder??t?.folder??Mr(n)),s={name:n,folder:i,aliases:ct([...t?.aliases??[],...e.aliases??[]]),required_create_fields:mh(e,t),required_create_repeatables:_h(e,t),options:gh(e,t),command_option_policies:hh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Hc(e,t){for(let n of e){let r=ch(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,yh(r,i))}}function bh(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=ph(o);i&&t.push(i)}}return t}function ae(e,t=null){let n=new Map;for(let c of lc)n.set(c.toLowerCase(),{name:c,folder:Te[c],aliases:[],required_create_fields:[...ih],required_create_repeatables:[...sh],options:[],command_option_policies:[]});Hc(e.item_types?.definitions??[],n),Hc(bh(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 Eh={json_markdown:".md",toon:".toon"},kh={".md":"json_markdown",".toon":"toon"};var tn=[".md",".toon"];function Fr(e){try{return vh(e),!0}catch{return!1}}function Th(e){try{let t=JSON.parse(wh(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Sh(e){let t=J.resolve(e);for(;;){let n=J.join(t,Vt),r=J.join(n,mr);if(Fr(r))return n;let o=J.join(t,mr);if(Fr(o)&&Th(o))return t;let i=J.dirname(t);if(i===t)return;t=i}}function Zc(e){return Sh(e)??J.resolve(e,Vt)}function oe(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=J.resolve(e,r);if(!Fr(ye(o))){let i=J.join(o,Vt);if(Fr(ye(i)))return i}return o}return Zc(e)}function Ci(e){let t=J.resolve(e),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):t}function ye(e){return J.join(e,mr)}function Ah(e,t,n=Te){let r=n[t]??Mr(t);return J.join(e,r)}function nn(e,t,n,r="toon",o=Te){return J.join(Ah(e,t,o),`${n}${Eh[r]}`)}function $r(e){let t=e.replaceAll("\\","/"),n=J.posix.extname(t).toLowerCase();return kh[n]??null}function Be(e,t){return J.join(e,"history",`${t}.jsonl`)}function Qc(e,t){return J.join(e,"locks",`${t}.lock`)}function jr(e){return J.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 iR=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 It(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,m=s[d-1]+1,_=i[d]+1,g=Math.min(f,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 el=Wt;function Ii(e){let t=e.trim().toLowerCase();return el.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 Ot(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function xh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function tl(e){return e?Ke(e):{}}function nl(e){return e?Ke(e):xh()}function Ke(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 rl=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 vR=new Set(rl);(function(){try{var e=typeof window<"u"?window:typeof 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 Ri=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"}]),Ch=new Set(Ri.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 Ni=[{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 Ur(e){return e.trim().toLowerCase().replaceAll("-","_")}function Ih(e){if(e===void 0)return;let t=Ur(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function Di(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)Di(n,t);return Object.freeze(e)}for(let n of Object.values(e))Di(n,t);return Object.freeze(e)}function Oh(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 Rh(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 Nh(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 Dh(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=Ur(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 Ph(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 Lh(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 Mh(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Pi=class{#e=new Map;#t=new Map;constructor(t=Ni){for(let n of t)this.register(n)}register(t){let n=Dh(t);if(Ph(t,n),Lh(t,n),Oh(t,n),Rh(t,n),Nh(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Ih(t.inverse),o=[...new Set((t.aliases??[]).map(Ur))].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:Mh(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?Di(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=Ur(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 rn(){return new Pi}var NR=rn();(function(){try{var e=typeof window<"u"?window:typeof 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]="7d9d8924-3186-5aab-ac36-164fb08624a8")}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 jh=5e3;async function il(e,t,n){let r=[];for(let o of e)try{await o.run(Ke(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function Uh(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 y(`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 y(`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 y(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Li(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:Ke(t.before),after:t.after===null?null:Ke(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 y(`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."]}))},jh),o.unref?.()})])}catch(i){throw i instanceof y?i:new y(`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)}Uh(r,n,t.operation)}}async function Mi(e,t){return il(e.onWrite,"onWrite",t)}async function Fi(e,t){return il(e.onRead,"onRead",t)}function zh(e){return{handled:!1,result:e.payload,warnings:[]}}function qh(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Bh(e){return{service:e.service,command:e.command?Ot(e.command):void 0,args:e.args?Ke(e.args):void 0,options:e.options?tl(e.options):void 0,global:e.global?nl(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:Ke(e.payload)}}function Gh(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 Vh(e,t){return Gh(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 Hh(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&Se(e,n.payload)}function Wh(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 $i(e,t){let n=qh(e,t.service);if(n.length===0)return zh(t);let r=[];for(let o of n)try{let i=Bh(t),s=await Promise.resolve(o.run(i));if(Hh(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Wh(o,Vh(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 R0=Object.freeze(pr());(function(){try{var e=typeof window<"u"?window:typeof 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 zr=null;var my=null;var _y=null,gy=null;var hy=[],yy=new py;function lt(){return yy.getStore()}var by=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function G(){let e=lt();return e?e.registrations:_y}function ji(e){if(!e)return;let t=lt();t?t.affectedItems.push(e):hy.push(e)}function qr(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"||by.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function be(e){let t=lt(),n=t?t.hooks:zr;return n?Mi(n,e):[]}async function Ui(e){let t=lt(),n=t?t.hooks:zr;n&&await Li(n,e)}async function Le(e){let t=lt(),n=t?t.hooks:zr;return n?Fi(n,e):[]}function Br(){let e=lt();return((e?e.hooks:zr)?.onRead?.length??0)>0}function wy(e,t){let n=lt(),r=n?n.commandContext:gy;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=lt(),r=n?n.services:my;return r?$i(r,wy(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as Hi}from"node:async_hooks";import{createHash as Iy}from"node:crypto";import Xe from"node:fs";import pl from"node:os";import Wr from"node:path";import{AsyncLocalStorage as vy}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 Ey=new vy,ll=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Gr(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Rn(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Gr(n.id,128),o=Gr(n.parent_id,128);if(r===void 0||!ll.test(r)||o!==void 0&&!ll.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Gr(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function zi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Gr(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function ky(e,t,n){let r=Ey.getStore(),o=zi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Rn(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={...zi(r?.provenance),...o,...zi(e?.provenance)},a=Rn(e?.episode,!1)??Rn(n,!1)??i??Rn(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 Vr(e,t){return ky(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as qi,promises as nD,readFileSync as Ty}from"node:fs";import Ye 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 Sy="session.json";function Bi(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Ay(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=Bi(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=>Bi(c,128)),a=t.focused_item_id===void 0||Bi(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function xy(e){return Ye.join(jr(e),Sy)}function Cy(e,t){let n=t.PM_PATH?.trim();if(n){let o=Ye.resolve(e,n);if(qi(Ye.join(o,"settings.json")))return o;let i=Ye.join(o,".agents","pm");if(qi(Ye.join(i,"settings.json")))return i}let r=Ye.resolve(e);for(let o=0;o<32;o+=1){let i=Ye.join(r,".agents","pm");if(qi(Ye.join(i,"settings.json")))return i;let s=Ye.dirname(r);if(s===r)break;r=s}}function dl(e){if(!e.key)return;let t=Cy(e.cwd,e.env);if(t)try{let n=JSON.parse(Ty(xy(t),"utf8"));return Ay(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]="8d89d381-5c6e-5f96-ba03-298fc6db9bba")}catch{}})();var Wi=["model","effort","role","topic","version"],Yr=new Hi,Oy=new Hi,Ki=new Hi,Yi=[{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:[]}],ml=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),Ry=Object.freeze({...ml,max_bytes:4194304}),Gi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Ny(e){let t=Nn(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"?Ry:ml,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 Dy=Object.freeze(Yi.filter(e=>e.harness!=="ci").map(Ny).sort((e,t)=>e.harness.localeCompare(t.harness))),Py=new Map,Ly=new Map;function V(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Rt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function Nn(e){let t=e.harness.trim().toLowerCase();if(!Gi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Rt(e.environment_keys),model_environment_keys:Rt(e.model_environment_keys),session_environment_keys:Rt(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),Rt(r)]).filter(([n])=>Gi.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"&&Gi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Rt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Rt(e.argv_markers).map(n=>n.toLowerCase()),client_names:Rt(e.client_names).map(n=>n.toLowerCase())}}var My=Yi.map(Nn);function Kr(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function _l(e=[]){let t=new Map(Yi.filter(o=>o.harness!=="ci").map(o=>[o.harness,Nn(o)]));for(let{adapter:o}of Py.values())t.set(o.harness,Nn(o.descriptor));let n=[...t.values(),...My.filter(o=>o.harness==="ci"),...[...Ly.values()].map(o=>o.descriptor),...Ki.getStore()?.descriptors??[],...e.map(Nn)],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 Xi(e,t){for(let n of t??[]){let r=V(e[n]);if(r)return r.slice(0,256)}}function Fy(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 gl(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 $y=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Nt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return $y.has(n)?n:void 0}function Vi(e,t){return V(e?.[t])?.slice(0,256)}var jy=1048576,ul=4194304,Hr=new Map,fl=Object.freeze({});function Uy(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=n,o=typeof r.message=="object"&&r.message!==null?r.message:void 0,i=t==="model"?o?.model:r.version;return V(i)?.slice(0,256)}function zy(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=Wr.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=Wr.join(t.home_dir??pl.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=Xe.openSync(s,"r");try{let c=Xe.fstatSync(a).size,l=Math.min(c,jy),d=Buffer.alloc(l);Xe.readSync(a,d,0,l,Math.max(0,c-l));let u=d.toString("utf8").split(`
|
|
11
|
-
`).reverse().slice(0,4096);for(let f of u){if(f.length===0||f.length>262144)continue;let
|
|
12
|
-
`).reverse().slice(0,r);r-=s.length;for(let a of s)if(
|
|
9
|
+
`}function fh(e,t={}){let n=Rn(e.metadata,t),r=Xc(n),o=Qt(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=eg(s),c;try{c=vi(a).value}catch(l){throw new y("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(!qc(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!qc(s[u],l[u]))??"document";throw new y(`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 xe(e,t={}){let n=Le(e);if(n)throw new y(`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=Kc(t);return r==="toon"?dh(e,o,t):lh(e,o,t)}function It(e,t={}){return(t.format??"toon")==="toon"?fh(e,t):uh(e,t)}function be(e,t={}){return{metadata:Rn(e.metadata,t),body:Qt(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 id from"fast-json-patch";import{AsyncLocalStorage as Oy}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 zr from"node:fs";import Ot from"node:path";import{fileURLToPath as ph}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 mh="@unbrained/pm-cli";function _h(e){try{return JSON.parse(zr.readFileSync(e,"utf8")).name===mh}catch{return!1}}function gh(e){let t=zr.existsSync(e)&&zr.statSync(e).isDirectory()?Ot.resolve(e):Ot.dirname(Ot.resolve(e));for(;;){let n=Ot.join(t,"package.json");if(zr.existsSync(n)&&_h(n))return t;let r=Ot.dirname(t);if(r===t)return;t=r}}function tn(e,t=[]){let n=ph(e),r=gh(n);return r||Ot.resolve(Ot.dirname(n),...t)}import{readFileSync as Fh,readdirSync as YR,statSync as $h}from"node:fs";import J from"node:path";import vh 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 lt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function hh(e){let t=e.key.trim();if(t.length===0)return null;let n=lt(e.aliases),r=e.description?.trim();return{key:t,values:lt(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 yh=e=>e,Zc=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function bh(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 wh(e,t){let n=new Map;for(let r of e??[]){let o=bh(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 Jc(e,t){return t?lt(e):void 0}function Ri(e){let t=e?.trim();return t&&t.length>0?t:void 0}function qr(e,t={}){let n=t.resolvePolicyCommand??yh,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=lt(e.aliases),l=(e.options??[]).map(u=>hh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=wh(e.command_option_policies,n);return{name:r,description:Ri(e.description),default_status:Ri(e.default_status),folder:Ri(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Jc(e.required_create_fields,o),required_create_repeatables:Jc(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 Eh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],kh=["dep","comment","note","learning","file","test","doc"],Ni=["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"],zR=["title","description","type","status","priority","tags","body",...Ni,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],qR=["title","description","body","status","closeReason","priority","type","tags",...Ni,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],el={"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"},BR={...el},GR={...el},tl=[["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"]],nl=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function rl(e){return Object.fromEntries(e)}var VR=rl([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...tl,["author","--author"],["message","--message"],["dep","--dep"],...nl]),HR=rl([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...tl,...nl,["author","--author"],["message","--message"],["force","--force"]]);function Br(e){let t=Th(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function ol(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=vh.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 Th(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 Sh(e){return qr(e,{resolvePolicyCommand:Zc})}function Nn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Ah(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:Nn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Nn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function xh(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 Ch(e){if(Array.isArray(e.options))return e.options.map(t=>Ah(t)).filter(t=>t!==null)}function Ih(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>xh(t)).filter(t=>t!==null)}function Oh(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:Nn(t,"aliases"),required_create_fields:Nn(t,"required_create_fields"),required_create_repeatables:Nn(t,"required_create_repeatables"),options:Ch(t),command_option_policies:Ih(t)}}function Rh(e,t){return e.required_create_fields?lt(e.required_create_fields):t?.required_create_fields??[]}function Nh(e,t){return e.required_create_repeatables?lt(e.required_create_repeatables):t?.required_create_repeatables??[]}function Dh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Ph(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Lh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=ol(e.folder??t?.folder??Br(n)),s={name:n,folder:i,aliases:lt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Rh(e,t),required_create_repeatables:Nh(e,t),options:Dh(e,t),command_option_policies:Ph(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Qc(e,t){for(let n of e){let r=Sh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Lh(r,i))}}function Mh(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=Oh(o);i&&t.push(i)}}return t}function le(e,t=null){let n=new Map;for(let c of hc)n.set(c.toLowerCase(),{name:c,folder:Se[c],aliases:[],required_create_fields:[...Eh],required_create_repeatables:[...kh],options:[],command_option_policies:[]});Qc(e.item_types?.definitions??[],n),Qc(Mh(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 jh={json_markdown:".md",toon:".toon"},Uh={".md":"json_markdown",".toon":"toon"};var nn=[".md",".toon"];function Gr(e){try{return $h(e),!0}catch{return!1}}function zh(e){try{let t=JSON.parse(Fh(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function qh(e){let t=J.resolve(e);for(;;){let n=J.join(t,Ht),r=J.join(n,vr);if(Gr(r))return n;let o=J.join(t,vr);if(Gr(o)&&zh(o))return t;let i=J.dirname(t);if(i===t)return;t=i}}function il(e){return qh(e)??J.resolve(e,Ht)}function ne(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=J.resolve(e,r);if(!Gr(we(o))){let i=J.join(o,Ht);if(Gr(we(i)))return i}return o}return il(e)}function Di(e){let t=J.resolve(e),n=J.dirname(t);return J.basename(t)==="pm"&&J.basename(n)===".agents"?J.dirname(n):t}function we(e){return J.join(e,vr)}function Bh(e,t,n=Se){let r=n[t]??Br(t);return J.join(e,r)}function rn(e,t,n,r="toon",o=Se){return J.join(Bh(e,t,o),`${n}${jh[r]}`)}function Vr(e){let t=e.replaceAll("\\","/"),n=J.posix.extname(t).toLowerCase();return Uh[n]??null}function Be(e,t){return J.join(e,"history",`${t}.jsonl`)}function sl(e,t){return J.join(e,"locks",`${t}.lock`)}function Hr(e){return J.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 eN=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 Rt(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,g=Math.min(f,p,_);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 al=Kt;function Pi(e){let t=e.trim().toLowerCase();return al.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 Nt(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Gh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function cl(e){return e?Ye(e):{}}function ll(e){return e?Ye(e):Gh()}function Ye(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 dl=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 gN=new Set(dl);(function(){try{var e=typeof window<"u"?window:typeof 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 Mi=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"}]),Vh=new Set(Mi.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 Fi=[{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 Wr(e){return e.trim().toLowerCase().replaceAll("-","_")}function Hh(e){if(e===void 0)return;let t=Wr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function $i(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)$i(n,t);return Object.freeze(e)}for(let n of Object.values(e))$i(n,t);return Object.freeze(e)}function Wh(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 Kh(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 Yh(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 Xh(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=Wr(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 Jh(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 Zh(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 Qh(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var ji=class{#e=new Map;#t=new Map;constructor(t=Fi){for(let n of t)this.register(n)}register(t){let n=Xh(t);if(Jh(t,n),Zh(t,n),Wh(t,n),Kh(t,n),Yh(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Hh(t.inverse),o=[...new Set((t.aliases??[]).map(Wr))].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:Qh(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?$i(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=Wr(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 on(){return new ji}var xN=on();(function(){try{var e=typeof window<"u"?window:typeof 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]="7d9d8924-3186-5aab-ac36-164fb08624a8")}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 ny=5e3;async function fl(e,t,n){let r=[];for(let o of e)try{await o.run(Ye(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function ry(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 y(`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 y(`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 y(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Ui(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:Ye(t.before),after:t.after===null?null:Ye(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 y(`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."]}))},ny),o.unref?.()})])}catch(i){throw i instanceof y?i:new y(`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)}ry(r,n,t.operation)}}async function zi(e,t){return fl(e.onWrite,"onWrite",t)}async function qi(e,t){return fl(e.onRead,"onRead",t)}function oy(e){return{handled:!1,result:e.payload,warnings:[]}}function iy(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function sy(e){return{service:e.service,command:e.command?Nt(e.command):void 0,args:e.args?Ye(e.args):void 0,options:e.options?cl(e.options):void 0,global:e.global?ll(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:Ye(e.payload)}}function ay(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 cy(e,t){return ay(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 ly(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&Ae(e,n.payload)}function dy(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 Bi(e,t){let n=iy(e,t.service);if(n.length===0)return oy(t);let r=[];for(let o of n)try{let i=sy(t),s=await Promise.resolve(o.run(i));if(ly(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=dy(o,cy(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 AD=Object.freeze(wr());(function(){try{var e=typeof window<"u"?window:typeof 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 Kr=null;var Ry=null;var Ny=null,Dy=null;var Py=[],Ly=new Oy;function dt(){return Ly.getStore()}var My=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function V(){let e=dt();return e?e.registrations:Ny}function Gi(e){if(!e)return;let t=dt();t?t.affectedItems.push(e):Py.push(e)}function Yr(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"||My.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function ve(e){let t=dt(),n=t?t.hooks:Kr;return n?zi(n,e):[]}async function Vi(e){let t=dt(),n=t?t.hooks:Kr;n&&await Ui(n,e)}async function Me(e){let t=dt(),n=t?t.hooks:Kr;return n?qi(n,e):[]}function Xr(){let e=dt();return((e?e.hooks:Kr)?.onRead?.length??0)>0}function Fy(e,t){let n=dt(),r=n?n.commandContext:Dy;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=dt(),r=n?n.services:Ry;return r?Bi(r,Fy(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as Ji}from"node:async_hooks";import{createHash as Hy}from"node:crypto";import Je from"node:fs";import wl from"node:os";import eo from"node:path";import{AsyncLocalStorage as $y}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 jy=new $y,gl=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Jr(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Dn(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Jr(n.id,128),o=Jr(n.parent_id,128);if(r===void 0||!gl.test(r)||o!==void 0&&!gl.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Jr(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Hi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Jr(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function Uy(e,t,n){let r=jy.getStore(),o=Hi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Dn(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={...Hi(r?.provenance),...o,...Hi(e?.provenance)},a=Dn(e?.episode,!1)??Dn(n,!1)??i??Dn(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 Zr(e,t){return Uy(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as Wi,promises as JD,readFileSync as zy}from"node:fs";import Xe 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 qy="session.json";function Ki(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function By(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=Ki(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=>Ki(c,128)),a=t.focused_item_id===void 0||Ki(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function Gy(e){return Xe.join(Hr(e),qy)}function Vy(e,t){let n=t.PM_PATH?.trim();if(n){let o=Xe.resolve(e,n);if(Wi(Xe.join(o,"settings.json")))return o;let i=Xe.join(o,".agents","pm");if(Wi(Xe.join(i,"settings.json")))return i}let r=Xe.resolve(e);for(let o=0;o<32;o+=1){let i=Xe.join(r,".agents","pm");if(Wi(Xe.join(i,"settings.json")))return i;let s=Xe.dirname(r);if(s===r)break;r=s}}function hl(e){if(!e.key)return;let t=Vy(e.cwd,e.env);if(t)try{let n=JSON.parse(zy(Gy(t),"utf8"));return By(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]="8d89d381-5c6e-5f96-ba03-298fc6db9bba")}catch{}})();var Zi=["model","effort","role","topic","version"],no=new Ji,Wy=new Ji,Qi=new Ji,es=[{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:[]}],vl=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),Ky=Object.freeze({...vl,max_bytes:4194304}),Yi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Yy(e){let t=Pn(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"?Ky:vl,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 Xy=Object.freeze(es.filter(e=>e.harness!=="ci").map(Yy).sort((e,t)=>e.harness.localeCompare(t.harness))),Jy=new Map,Zy=new Map;function H(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Dt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function Pn(e){let t=e.harness.trim().toLowerCase();if(!Yi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Dt(e.environment_keys),model_environment_keys:Dt(e.model_environment_keys),session_environment_keys:Dt(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),Dt(r)]).filter(([n])=>Yi.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"&&Yi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Dt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Dt(e.argv_markers).map(n=>n.toLowerCase()),client_names:Dt(e.client_names).map(n=>n.toLowerCase())}}var Qy=es.map(Pn);function to(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function El(e=[]){let t=new Map(es.filter(o=>o.harness!=="ci").map(o=>[o.harness,Pn(o)]));for(let{adapter:o}of Jy.values())t.set(o.harness,Pn(o.descriptor));let n=[...t.values(),...Qy.filter(o=>o.harness==="ci"),...[...Zy.values()].map(o=>o.descriptor),...Qi.getStore()?.descriptors??[],...e.map(Pn)],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 ts(e,t){for(let n of t??[]){let r=H(e[n]);if(r)return r.slice(0,256)}}function eb(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 kl(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 H(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return H(i.slice(s.length+1))?.slice(0,256)}}var tb=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Pt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return tb.has(n)?n:void 0}function Xi(e,t){return H(e?.[t])?.slice(0,256)}var nb=1048576,yl=4194304,Qr=new Map,bl=Object.freeze({});function rb(e,t){let n;try{n=JSON.parse(e)}catch{return}let r=n,o=typeof r.message=="object"&&r.message!==null?r.message:void 0,i=t==="model"?o?.model:r.version;return H(i)?.slice(0,256)}function ob(e,t,n){let r=H(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=eo.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=eo.join(t.home_dir??wl.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=Je.openSync(s,"r");try{let c=Je.fstatSync(a).size,l=Math.min(c,nb),d=Buffer.alloc(l);Je.readSync(a,d,0,l,Math.max(0,c-l));let u=d.toString("utf8").split(`
|
|
11
|
+
`).reverse().slice(0,4096);for(let f of u){if(f.length===0||f.length>262144)continue;let p=rb(f,e);if(p)return p}}finally{Je.closeSync(a)}}catch{return}}function ib(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=Je.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=eo.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 sb(e){if(e<=yl)return[{offset:0,length:e}];let t=Math.floor(yl/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function ab(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??=H(o?.model)?.slice(0,256),e.effort??=H(o?.effort)?.slice(0,256)}function cb(e,t){let n={},r=4096;for(let o of sb(t)){let i=Buffer.alloc(o.length);Je.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
|
|
12
|
+
`).reverse().slice(0,r);r-=s.length;for(let a of s)if(ab(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function lb(e,t,n){let r=H(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=eo.join(t.home_dir??wl.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=Qr.get(i);if(s)return s[e];let a=ib(o,r);if(!a){Qr.set(i,bl);return}try{let c=Je.openSync(a,"r");try{let l=Je.fstatSync(c).size,d=cb(c,l);return Qr.set(i,d),d[e]}finally{Je.closeSync(c)}}catch{Qr.set(i,bl);return}}function db(e,t,n,r){let o=Qi.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(H(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return ob(e,t,n);if(s==="codex_session_file")return lb(e,t,n);if(s==="ai_agent_version"){let a=H(n.AI_AGENT);return!a||!r||!to(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function ub(e,t,n){if(e==="ai_agent_version"){let r=H(n.AI_AGENT);return r!==void 0&&to(r,t.harness)}return e==="codex_session_file"?H(n.CODEX_THREAD_ID)!==void 0:H(n.CLAUDE_CODE_SESSION_ID)!==void 0}function ns(e){return e||(Wy.getStore()??{env:process.env,argv:process.argv})}function fb(e,t,n,r){let o=e.environment_keys.some(a=>H(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return to(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||to(r,a));return o||i||s}function pb(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 mb(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function _b(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Zi,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=Pt(e,H(n[s])?.slice(0,256)),d=Pt(e,kl(t.argv??[],e)),l=Pt(e,eb(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=Xi(o?.provenance,e),_=Pt(e,ts(n,u[e])),g=Pt(e,Xi(f,e)),b=Pt(e,Xi(t.provenance,e)),T=db(e,t,n,r);return mb([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[g,"mcp_client"],[b,"host"],[T,"probe"]])??pb(e,i)??(l?{value:l,source:"argv"}:void 0)}function gb(e,t){if(!(!e||!t))return Hy("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function hb(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Zi,...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=_b(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 rs(e){let t=ns(e),n=t.env??{},r=El(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(_=>fb(_,n,o,i)),a=Zr(t,n),c=[ts(n,s?.session_environment_keys),H(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=gb(s?.harness,c),d=hl({cwd:t.cwd??process.cwd(),env:n,key:l}),u=hb(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(_=>_[1]!==void 0))}function yb(e,t,n,r,o,i){let s=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...s?{resolver:s}:{},rule_version:"v1"};if(i)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(s){let a=ub(s,n,r);return{status:a&&o?"failed":"unavailable",reason:a?o?"resolver_failed":"probes_disabled":"harness_unavailable",resolver:s,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 os(e){let t=ns(e),n=rs(t),r=El(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Qi.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(H(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Zr(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,ts(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,kl(t.argv??[],"role")].some(l=>{let d=H(l)?.slice(0,256);return d!==void 0&&Pt("role",d)===void 0}),c=Object.fromEntries(Zi.map(l=>[l,yb(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function bb(e,t,n){let r=ns(n),o=rs(r);if(e!==void 0){let s=H(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=H(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=H(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Tl(e){let t=no.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Sl(e){let t=no.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 is(e){let t=no.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Fe(e,t){let n=bb(e,t);return no.enterWith(n),n.author}import ss from"node:fs/promises";import sn from"node:path";import{createRequire as wb}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]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function ut(e,t){let n=await X(e);if(n===null)return[];if(await Me({path:e,scope:"project"}),n.trim()==="")return[];let r=Le(n);if(r)throw new y(`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 y(`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]="a84b308f-7eef-535c-9531-b33b0775c651")}catch{}})();var vb="history-event-index.sqlite",Eb="2";function Al(e){return sn.join(e,"runtime",vb)}function kb(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function Tb(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?kb(t):null}var ro;function Sb(){return ro!==void 0||(ro=Tb(process.versions.node,wb(import.meta.url))),ro}function Ab(e,t){e.prepare(`INSERT INTO events(
|
|
13
13
|
stream_id, stream_offset, ts, author, agent_harness,
|
|
14
14
|
agent_instance, op, entry_json
|
|
15
|
-
) 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 wl(e,t){let n=on.dirname(on.dirname(e)),r=bl(n);try{await ts.access(r)}catch{return}let o=cb();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==ib)throw new TypeError("Unsupported history event index version");let a=on.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);lb(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await ts.rm(r,{force:!0})}}async function Jr(e){await ts.rm(bl(on.dirname(on.dirname(e))),{force:!0})}import ss from"node:fs/promises";import sn 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 Hb}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 vl(e,t,n){if(e&&t)throw new y(`${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 db=1,ub=4096;var PD=Object.freeze({version:db,max_length:ub});(function(){try{var e=typeof window<"u"?window:typeof 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]="9afc5057-afcd-5d6c-a4c1-c2883640fc50")}catch{}})();var Zr=[...[["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"}))],mb=Object.fromEntries(Zr.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]="3935bae8-0a40-59ea-aca6-64e238d1f318")}catch{}})();var _b=[...wn],gb=[...fr],hb=[...Zo],yb=[...Qo],bb=[...ei],wb=[...ti],Qr=["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 El=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],kl=["reopen"],Tl={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},ut=Object.freeze(Qr.flatMap(e=>e in Tl?[]:e==="extension"||e==="package"?[...El.map(t=>`${e}-${t}`),e]:e==="item"?kl.map(t=>`item-${t}`):[e])),Sl=Object.freeze(Zr.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&ut.includes(e.alias)).map(e=>e.alias)),vb=Object.freeze(ut.filter(e=>!Sl.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 Al=["full","compact","brief","summary","counts"];var xl=["error","warning","validation_summary","recovery_bundle"],Cl=["full","omit_explanation","limit_collections","compact_recovery","action_only"],Eb=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"]),kb=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Tb=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Sb={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Ab=3,xb=2,Cb=192,Ib={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Il=xl.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:Ib[e],minimum_max_estimated_tokens:Cb,degradation_ladder:Cl,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),GD=new Map(Il.map(e=>[e.diagnostic_class,e]));function Ol(e){let[t=""]=e.trim().split(/\s+/u);return Eb.has(t)?"mutation":kb.has(t)?"discovery":Tb.has(t)?"governance":"read"}function Rl(e,t=Ol(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=Sb[t];return Nl({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*Ab/xb)},degradation_ladder:Al,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Nl(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 Dl=Qr.map(e=>Rl(e)),VD=new Map(Dl.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]="1c73c31e-6246-5730-8c8a-d3ba7c9ec112")}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]="642f6dec-c0b2-5377-a401-dfa4f8ef6a2a")}catch{}})();var Pl=256,to=1e4,Nb=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Db=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var oP=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&Nb.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Pl,reason:`token_budget must be a safe integer of at least ${Pl}.`},{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<=to&&e.seen_item_ids.every(t=>typeof t=="string"&&Db.test(t)),reason:`seen_item_ids must contain at most ${to} 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]="76c9c2d0-951d-579e-916e-e8d54d4a8be9")}catch{}})();var Ll=["include","amount","cost","encoding"],Ml=["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"],jb=["canonical","legacy","intent","default"],ns={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Fl=Object.freeze(Ll.map(e=>ns[e])),$l=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Ub={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:{}},zb=new Set(["--collapse","--fields","--section"]),jl=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 qb(e){return e.slice(2).replaceAll("-","_")}function Bb(e,t){let n=jl[e];if(n!==void 0)return n;let r=t==="include"?zb.has(e)?"<csv>":qb(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${ns[t]} ${r}.`}function Gb(e){let t=Ub[e],n=Object.freeze(Object.fromEntries(Ll.map(r=>[r,Object.freeze({dimension:r,canonical_option:ns[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:jl[o]===void 0?"replacement":"behavior_preserving",migration_hint:Bb(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:jb,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix"})}var Vb=Object.freeze(Ml.map(Gb)),xP=new Map(Vb.map(e=>[e.command,e]));function eo(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 Ml.includes(i)?i: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]="da15ca02-02cc-5886-8c82-610939b8581c")}catch{}})();var qP=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"}]),BP=new 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]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();import{encode as dL}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 uL=new Set(Object.values(h));var Ul=!1;function rs(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Kb(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function Yb(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function os(e){if(e==="stdout"){Kb();return}Yb()}function zl(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function Xb(){Ul||(Ul=!0,process.stdout.on("error",e=>{if(rs(e)){os("stdout");return}zl(e)}),process.stderr.on("error",e=>{if(rs(e)){os("stderr");return}zl(e)}))}function Jb(e,t){Xb();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(rs(n))return os(e),!1;throw n}}function is(e){return Jb("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 Zb=sn.join("runtime","history-drift-cache.json"),Bl={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 Gl(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function as(e){let t=sn.join(e,Zb),n=!1,r="invalid_cache_path";try{n=(await ss.stat(await ss.realpath(e))).isDirectory()}catch(o){let i=Gl(o);r=i===void 0?"unknown":Bl[i]??"filesystem_error"}if(!n){is(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
16
|
-
`);return}try{await
|
|
17
|
-
`)}}async function
|
|
15
|
+
) 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 xl(e,t){let n=sn.dirname(sn.dirname(e)),r=Al(n);try{await ss.access(r)}catch{return}let o=Sb();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Eb)throw new TypeError("Unsupported history event index version");let a=sn.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);Ab(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await ss.rm(r,{force:!0})}}async function oo(e){await ss.rm(Al(sn.dirname(sn.dirname(e))),{force:!0})}import fs from"node:fs/promises";import an 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 uw}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 Cl(e,t,n){if(e&&t)throw new y(`${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 xb=1,Cb=4096;var IP=Object.freeze({version:xb,max_length:Cb});(function(){try{var e=typeof window<"u"?window:typeof 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]="9afc5057-afcd-5d6c-a4c1-c2883640fc50")}catch{}})();var io=[...[["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"}))],Rb=Object.fromEntries(io.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]="3935bae8-0a40-59ea-aca6-64e238d1f318")}catch{}})();var Nb=[...wn],Db=[...br],Pb=[...oi],Lb=[...ii],Mb=[...si],Fb=[...ai],so=["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 Il=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Ol=["reopen"],Rl={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},ft=Object.freeze(so.flatMap(e=>e in Rl?[]:e==="extension"||e==="package"?[...Il.map(t=>`${e}-${t}`),e]:e==="item"?Ol.map(t=>`item-${t}`):[e])),Nl=Object.freeze(io.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&ft.includes(e.alias)).map(e=>e.alias)),$b=Object.freeze(ft.filter(e=>!Nl.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 Dl=["full","compact","brief","summary","counts"];var Pl=["error","warning","validation_summary","recovery_bundle"],Ll=["full","omit_explanation","limit_collections","compact_recovery","action_only"],jb=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"]),Ub=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),zb=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),qb={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Bb=3,Gb=2,Vb=192,Hb={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Ml=Pl.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:Hb[e],minimum_max_estimated_tokens:Vb,degradation_ladder:Ll,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),jP=new Map(Ml.map(e=>[e.diagnostic_class,e]));function Fl(e){let[t=""]=e.trim().split(/\s+/u);return jb.has(t)?"mutation":Ub.has(t)?"discovery":zb.has(t)?"governance":"read"}function $l(e,t=Fl(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=qb[t];return jl({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*Bb/Gb)},degradation_ladder:Dl,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function jl(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 Ul=so.map(e=>$l(e)),UP=new Map(Ul.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 Kb=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"]),Yb=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:Kb}),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 zl=256,ao=1e4,Jb=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Zb=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var QP=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&Jb.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=zl,reason:`token_budget must be a safe integer of at least ${zl}.`},{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<=ao&&e.seen_item_ids.every(t=>typeof t=="string"&&Zb.test(t)),reason:`seen_item_ids must contain at most ${ao} 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]="d084da05-c967-58f1-afe4-069f09838e6f")}catch{}})();var ql=["include","amount","cost","encoding"],Bl=["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"],iw=["canonical","legacy","intent","default"],as={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Gl=Object.freeze(ql.map(e=>as[e])),Vl=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Hl={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:{}},Wl=new Set(["--collapse","--fields","--section"]),cs=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 Kl(e){return e.slice(2).replaceAll("-","_")}function sw(e,t){let n=cs[e];if(n!==void 0)return n;let r=t==="include"?Wl.has(e)?"<csv>":Kl(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${as[t]} ${r}.`}function aw(e){let t=Hl[e],n=Object.freeze(Object.fromEntries(ql.map(r=>[r,Object.freeze({dimension:r,canonical_option:as[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:cs[o]===void 0?"replacement":"behavior_preserving",migration_hint:sw(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:iw,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...lw(e).keys()])})}var cw=Object.freeze(Bl.map(aw)),vL=new Map(cw.map(e=>[e.command,e]));function Ln(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 Bl.includes(i)?i:void 0}function lw(e){let t=Ln(e);return t?new Map((Hl[t].include??[]).filter(n=>!Wl.has(n)&&cs[n]===void 0).map(n=>[Kl(n),dw(n)])):new Map}function dw(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 ML=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"}]),FL=new uw;(function(){try{var e=typeof window<"u"?window:typeof 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 oM}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 iM=new Set(Object.values(h));var Yl=!1;function ls(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function pw(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function mw(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function ds(e){if(e==="stdout"){pw();return}mw()}function Xl(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function _w(){Yl||(Yl=!0,process.stdout.on("error",e=>{if(ls(e)){ds("stdout");return}Xl(e)}),process.stderr.on("error",e=>{if(ls(e)){ds("stderr");return}Xl(e)}))}function gw(e,t){_w();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(ls(n))return ds(e),!1;throw n}}function us(e){return gw("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 hw=an.join("runtime","history-drift-cache.json"),Zl={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 Ql(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function ps(e){let t=an.join(e,hw),n=!1,r="invalid_cache_path";try{n=(await fs.stat(await fs.realpath(e))).isDirectory()}catch(o){let i=Ql(o);r=i===void 0?"unknown":Zl[i]??"filesystem_error"}if(!n){us(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
16
|
+
`);return}try{await fs.rm(t,{force:!0})}catch(o){let i=Ql(o);if(te(o))return;let s=i===void 0?"unknown":Zl[i]??"filesystem_error";us(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
17
|
+
`)}}async function Ze(e){let t=an.dirname(an.resolve(e));an.basename(t)==="history"&&await ps(an.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]="f7cf18cb-0068-58ad-bd7f-759a5d91eb9f")}catch{}})();var $e=2,cn=[1,2];function co(e,t){return(e??"").localeCompare(t??"")}function ed(e,t){return(e??0)-(t??0)}function pt(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function yw(e,t){return[e.scope.localeCompare(t.scope),co(e.path,t.path),co(e.command,t.command),ed(e.timeout_seconds,t.timeout_seconds),co(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,pt(e.env_clear,t.env_clear,[]),pt(e.env_set,t.env_set,{}),pt(e.assert_stdout_contains,t.assert_stdout_contains,[]),pt(e.assert_stdout_regex,t.assert_stdout_regex,[]),pt(e.assert_stderr_contains,t.assert_stderr_contains,[]),pt(e.assert_stderr_regex,t.assert_stderr_regex,[]),ed(e.assert_stdout_min_lines,t.assert_stdout_min_lines),pt(e.assert_json_field_equals,t.assert_json_field_equals,{}),pt(e.assert_json_field_gte,t.assert_json_field_gte,{}),co(e.note,t.note)].find(r=>r!==0)??0}function bw(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function ww(e,t){let n=bw(t);if(n.length===0)return!0;let r=e;for(let o of n){if(Array.isArray(r)){if(o==="-"||!/^(0|[1-9]\d*)$/.test(o))return!1;let s=Number(o);if(!Number.isInteger(s)||s<0||s>=r.length)return!1;let a=r[s];if(a===void 0)return!1;r=a;continue}if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];if(i===void 0)return!1;r=i}return!0}function vw(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!ww(r,o.path)?{...o,op:"add"}:o;n.push(i),r=id.applyPatch(r,[i],!0,!0).newDocument}return n}function ms(e,t){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=be(e),o=t===1&&r.metadata.tests?{...r.metadata,tests:[...r.metadata.tests].sort(yw)}:r.metadata;return{front_matter:it(o,Te),body:r.body}}function td(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=be(e);return{metadata:it(n.metadata,Te),body:n.body}}function Mn(e,t){if(!cn.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return ce(O(ms(e,t)))}function Fn(e){let t=ms(e.before,$e),n=ms(e.after,$e),r=td(e.before),o=td(e.after),i=id.compare(r,o),s=vw(r,i),a=Sl(e.author),c=a.harness?Object.fromEntries(Object.entries(os().provenance_outcomes).filter(([,d])=>d.resolver!==void 0&&d.status!=="resolved")):void 0,l=c===void 0||Object.keys(c).length===0?e.context:{...e.context,agent_provenance_outcomes:c};return{ts:e.nowIso,author:e.author,author_source:e.authorSource??Tl(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:ce(O(t)),after_hash:ce(O(n)),item_hash_version:$e,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ew(e){let t=e.ts.trim();return t.length>0?t:q()}function rd(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function lo(e,t){let n=Ew(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(nd(r))return JSON.stringify(rd(r,n))}catch{}return e}return nd(e)?JSON.stringify(rd(e,n)):JSON.stringify(e)}async function uo(e,t){let n=await Ge("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Xt(e,lo(n.result,t)),await Ze(e),await oo(e);return}if(typeof n.result=="object"&&n.result!==null){let r=n.result;if(r.skip===!0)return;let o=typeof r.history_path=="string"?r.history_path:e;if(typeof r.line=="string"){await Xt(o,lo(r.line,t)),await Ze(o),await oo(o);return}await Xt(o,lo(r.entry??t,t)),await Ze(o),await oo(o);return}}await Xt(e,lo(t,t)),await Ze(e),await xl(e,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]="bf8797ec-53d3-5d23-8a6e-8296a027ddf2")}catch{}})();var gs={metadata:{},body:""};function $n(){return structuredClone(gs)}function Ce(e,t=$e){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Mn(jn(e),t)}catch{}return ce(O({replay_fallback:!0,metadata:e.metadata,body:e.body}))}function jn(e){return{metadata:e.metadata,body:e.body}}function hs(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=be(e);return{metadata:it(t.metadata,Te),body:t.body}}function sd(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function kw(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Un(e){return Array.isArray(e)?e.filter(kw).map(t=>({...t,path:sd(t.path),from:typeof t.from=="string"?sd(t.from):void 0})):[]}function Tw(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 ln(e,t){try{let n=Un(t),r=_s.applyPatch(structuredClone(e),n,!0,!1).newDocument;return Tw(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 Sw(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&cn.includes(t)))]}function Aw(e,t){return e!==void 0?[e]:t===void 0?[1,$e]:[t]}function Lt(e){let t=$n(),n,r;for(let o=0;o<e.length;o+=1){let i=e[o],s=i.item_hash_version;if(s!==void 0&&!cn.includes(s))return{ok:!1,errors:[`verify_failed:unsupported_item_hash_version:${String(s)}:entry_${o+1}`]};let a=ln(t,i.patch);if(!a.ok)return{ok:!1,errors:[`verify_failed:patch_apply_failed:entry_${o+1}`]};let l=Aw(s,r).filter(u=>Ce(t,u)===i.before_hash);if(l.length===0)return{ok:!1,errors:[`verify_failed:before_hash_mismatch:entry_${o+1}`]};let d=l.find(u=>Ce(a.document,u)===i.after_hash);if(d===void 0)return{ok:!1,errors:[`verify_failed:after_hash_mismatch:entry_${o+1}`]};t=a.document,n=d,s!==void 0&&(r=d)}return{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Mt(e){let t=Lt(e);return{ok:t.ok,errors:t.errors}}function ad(e,t){try{return{ok:!0,document:_s.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function xw(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Un(t)){let c=ad(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=ad(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 ys(e){let t=Sw(e);if(t.length===1)return t[0];let n=Lt(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:$e}function fo(e,t=ys(e)){let n=e.findIndex(u=>u.item_hash_version!==void 0&&!cn.includes(u.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let r=$n(),o=[],i=[],s=0,a=0,c=0,l=0,d=t!==1||e.some(u=>u.item_hash_version!==void 0);for(let u=0;u<e.length;u+=1){let f=e[u],p=Ce(r,t),_=ln(r,f.patch),g,b,T=!1,k=0,I=0;if(_.ok)g=_.document,b=f.patch;else{let P=xw(r,f.patch);g=P.document,b=_s.compare(r,g),T=!0,k=P.convertedReplaceToAdd,I=P.skippedOps,c+=k,l+=I,a+=1}let x=Ce(g,t),v=p!==f.before_hash||x!==f.after_hash;v&&(s+=1);let N={...f,patch:b,before_hash:p,after_hash:x};d?N.item_hash_version=t:delete N.item_hash_version,o.push(N),i.push({index:u+1,rehashed:v,patch_repaired:T,converted_replace_to_add:k,skipped_ops:I}),r=g}return{entries:o,finalDocument:r,entriesRehashed:s,entriesPatchRepaired:a,convertedReplaceToAdd:c,skippedOps:l,details:i,itemHashVersion:t,explicitItemHashVersion:d}}function mt(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
18
18
|
`)}
|
|
19
|
-
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function
|
|
19
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function bs(e,t){let n=Le(e);if(n)throw new y(`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 y(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,h.GENERIC_FAILURE)}}return r}function _t(e){return O({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Cw(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&_t(e[r])===_t(t[r]);)r+=1;return r}function Ss(e,t,n){bs(e,"base");let r=bs(t,"ours"),o=bs(n,"theirs"),i=Cw(r,o);if(i===r.length&&i===o.length)return{merged:mt(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:mt(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:mt(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(_t)),c=o.slice(i).filter(u=>!a.has(_t(u))),l=[...s,...c].sort((u,f)=>{let p=pe(u.ts,f.ts);if(p!==0)return p;let _=a.has(_t(u)),g=a.has(_t(f));return _!==g?Number(g)-Number(_):_t(u).localeCompare(_t(f))}),d=fo([...r.slice(0,i),...l]);return{merged:mt(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 ws(e,t){let n=Le(e);if(n)throw new y(`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 y(`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 y(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,h.GENERIC_FAILURE);r.push(a)}return r}function po(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
20
20
|
`)}
|
|
21
|
-
`}function
|
|
22
|
-
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as
|
|
23
|
-
`)
|
|
24
|
-
`)
|
|
25
|
-
`);let r=await ad(e,t.item_path);if(r!==null){let o=we.join(Ts(r),ao(t.id));if(await q(o)){let i=JSON.parse(await sd(o,"utf8"));await F(o,`${JSON.stringify({...i,state:"reconciled",reconciled_at:z()},null,2)}
|
|
26
|
-
`)}}}async function Aw(e){let t=await ln(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:z()}}import{readFile as oE,writeFile as iE}from"node:fs/promises";import sE 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 Ft=new Set(ke),xw=Object.freeze({get size(){return Ft.size},has(e){return Ft.has(e)},entries(){return Ft.entries()},keys(){return Ft.keys()},values(){return Ft.values()},forEach(e,t){Ft.forEach(n=>e.call(t,n,n,xw))},[Symbol.iterator](){return Ft.values()}});function Cw(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Iw(e){return typeof e!="string"?null:Ii(e)}function Ow(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Cw(r.name),i=Iw(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new y(`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 Ze(e){return[...Ow(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 ie={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ie,P=e=>typeof e=="boolean"?{ok:!0,value:e}:ie;function j(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?ie:{ok:!0,value:t}}function M(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ie}function T(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ie;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ie;r.push(i.value)}return{ok:!0,value:r}}}function xs(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}:ie}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function lo(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ie;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ie;n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ie;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ie;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var Rw=I({key:w,values:T(w),required:p(P),aliases:p(T(w)),description:p(w)}),Nw=I({command:M("create","update"),option:w,required:p(P),visible:p(P),enabled:p(P)}),Dw=I({name:w,description:p(w),default_status:p(w),folder:p(w),aliases:p(T(w)),required_create_fields:p(T(w)),required_create_repeatables:p(T(w)),options:p(T(Rw)),command_option_policies:p(T(Nw))}),Pw=I({id:w,aliases:p(T(w)),roles:p(T(M(..._r))),description:p(w),order:p(j())}),Lw=I({key:w,metadata_key:p(w),front_matter_key:p(w),cli_flag:p(w),cli_aliases:p(T(w)),description:p(w),type:p(M(...Wt)),commands:p(T(M(...gr))),repeatable:p(P),required:p(P),required_on_create:p(P),required_types:p(T(w)),allow_unset:p(P)}),Mw=e=>{if(!Array.isArray(e)||e.length!==2)return ie;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ie:{ok:!0,value:[t,n]}},Fw=I({type:w,allowed_transitions:T(Mw)}),$w=p(I({version:p(j({int:!0})),files:p(I({types:p(w),statuses:p(w),fields:p(w),workflows:p(w)})),statuses:p(T(Pw)),fields:p(T(Lw)),workflow:p(I({draft_status:p(w),open_status:p(w),in_progress_status:p(w),blocked_status:p(w),close_status:p(w),canceled_status:p(w)})),type_workflows:p(T(Fw)),unknown_field_policy:p(M(...hr))})),jw=p(I({preset:p(M(...dc)),ownership_enforcement:p(M("none","warn","strict")),create_mode_default:p(M("progressive","strict")),close_validation_default:p(M("off","warn","strict")),require_close_reason:p(P),parent_reference:p(M("warn","strict_error")),metadata_profile:p(M("core","strict","custom")),force_required_for_stale_lock:p(P),create_default_type:p(w),workflow_enforcement:p(M("off","warn","strict")),duplicate_detection_mode:p(M("off","advisory","strict")),duplicate_detection_threshold:p(j({min:0,max:1})),duplicate_detection_limit:p(j({int:!0,min:0,max:20}))})),Uw=I({name:w,disabled:p(P),require_trusted:p(P),require_provenance:p(P),sandbox_profile:p(M("none","restricted","strict")),allowed_capabilities:p(T(w)),blocked_capabilities:p(T(w)),allowed_surfaces:p(T(w)),blocked_surfaces:p(T(w)),allowed_commands:p(T(w)),blocked_commands:p(T(w)),allowed_actions:p(T(w)),blocked_actions:p(T(w)),allowed_services:p(T(w)),blocked_services:p(T(w))}),As=M("block","warn"),zw=e=>typeof e=="string"?As(e):I({global:p(As),project:p(As)})(e),qw=p(I({mode:p(M("off","warn","enforce")),trust_mode:p(M("off","warn","enforce")),pm_max_version_exceeded_mode:p(zw),require_provenance:p(P),trusted_extensions:p(T(w)),default_sandbox_profile:p(M("none","restricted","strict")),allowed_extensions:p(T(w)),blocked_extensions:p(T(w)),allowed_capabilities:p(T(w)),blocked_capabilities:p(T(w)),allowed_surfaces:p(T(w)),blocked_surfaces:p(T(w)),allowed_commands:p(T(w)),blocked_commands:p(T(w)),allowed_actions:p(T(w)),blocked_actions:p(T(w)),allowed_services:p(T(w)),blocked_services:p(T(w)),extension_overrides:p(T(Uw))})),$t=xs(128),Bw=I({harness:xs(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(T($t,64)),model_environment_keys:p(T($t,64)),session_environment_keys:p(T($t,64)),provenance_environment_keys:p(lo(T($t,64))),provenance_resolvers:p(lo(M("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(T($t,64)),argv_markers:p(T($t,64)),client_names:p(T($t,64))}),Gw=I({version:j({int:!0}),id_prefix:w,ids:p(I({token_length:p(j({int:!0,min:4,max:12}))})),author_default:w,agent_identity:p(I({probes_enabled:p(P),identity_vocabulary:p(I({version:j({int:!0,positive:!0}),aliases:lo(xs(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:T(Bw)})),mutation_guard:p(I({require_attributed_author:p(P),secret_guard:p(M("off","advise","block")),stale_in_progress_hours:p(j({int:!0,positive:!0}))})),item_format:p(M("toon","json_markdown")),locks:I({ttl_seconds:j({int:!0}),wait_ms:p(j({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(j({int:!0,positive:!0}))})),output:I({default_format:M("toon","json")}),ux:p(I({deprecation_hints:p(P)})),history:p(I({missing_stream:M("auto_create","strict_error"),compact_policy:p(I({enabled:p(P),max_entries:p(j({int:!0,positive:!0})),trigger:p(M("health_warn","auto"))}))})),validation:p(I({sprint_release_format:M("warn","strict_error"),parent_reference:p(M("warn","strict_error")),metadata_profile:p(M("core","strict","custom")),metadata_required_fields:p(T(w)),lifecycle_stale_blocker_reason_patterns:p(T(w)),lifecycle_closure_like_blocked_reason_patterns:p(T(w)),lifecycle_closure_like_resolution_patterns:p(T(w)),lifecycle_closure_like_actual_result_patterns:p(T(w)),estimate_defaults_by_type:p(lo(j({int:!0,positive:!0})))})),governance:jw,workflow:p(I({definition_of_done:T(w)})),testing:p(I({record_results_to_items:P,allow_untrusted_linked_tests:p(P)})),telemetry:p(I({enabled:P,first_run_prompt_completed:p(P),capture_level:p(M("minimal","redacted","max")),endpoint:p(w),installation_id:p(w),retention_days:p(j({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(P),declined:p(P),declined_at:p(w),template_version:p(j({int:!0,positive:!0})),last_checked_files:p(T(w))})),item_types:p(I({definitions:T(Dw)})),schema:$w,context:p(I({default_depth:p(M("brief","standard","deep")),activity_limit:p(j({int:!0,positive:!0})),stale_threshold_days:p(j({int:!0,positive:!0})),sections:p(I({hierarchy:p(P),activity:p(P),progress:p(P),recently_created:p(P),unparented:p(P),blockers:p(P),files:p(P),workload:p(P),staleness:p(P),tests:p(P)}))})),extensions:I({enabled:T(w),disabled:T(w),policy:qw}),search:I({score_threshold:j(),hybrid_semantic_weight:p(j()),max_results:j({int:!0}),embedding_model:w,embedding_corpus_max_characters:p(j()),embedding_batch_size:j({int:!0}),embedding_timeout_ms:p(j({int:!0})),scanner_max_batch_retries:j({int:!0}),provider:p(w),corpus_fields:p(T(w)),mutation_refresh_policy:p(M("cache_only","semantic_configured","semantic_auto")),query_expansion:p(I({enabled:p(P),provider:p(w)})),rerank:p(I({enabled:p(P),model:p(w),top_k:p(j({int:!0,positive:!0}))})),bm25:p(I({k1:p(j()),b:p(j())}))}),providers:I({openai:I({base_url:w,api_key:w,model:w}),ollama:I({base_url:w,model:w})}),vector_store:I({adapter:p(w),collection_name:p(w),qdrant:I({url:w,api_key:w}),lancedb:I({path:w})})});function ld(e){let t=Gw(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import jn from"node:path";import Qe from"node:fs/promises";import Cs from"node:path";import{randomUUID as Vw}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 Hw(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 pd(e){try{let t=await Qe.readFile(e,"utf8");return await Le({path:e,scope:"project"}),Hw(t)}catch(t){return te(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Is(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function md(e,t){await be({path:e,scope:"project",op:t})}function Ww(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:z(),ttl_seconds:n}}async function Kw(e,t,n,r){await Qe.mkdir(Cs.dirname(e),{recursive:!0});let o=await Qe.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Ww(t,n,r),null,2)}
|
|
27
|
-
`,"utf8")}finally{await o.close()}await md(e,"lock:create")}async function _d(e,t){try{return await Qe.unlink(e),await md(e,t),!0}catch{return!1}}function gd(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 Yw(e){return e?.owner?` (owner ${e.owner})`:""}var Xw=25,Jw=200,Zw=250,Qw=3,ev=".stale-cleanup",hd="owner.json",tv=1e4,nv=5*6e4;function dd(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 rv(e){let t=process.env.PM_LOCK_WAIT_MS,n=dd(t);if(n!==void 0)return n;let r=dd(e);return r!==void 0?r:0}function ov(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function yd(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new y(`Item ${e} is locked${Yw(t)}${r}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:Zw}})}function iv(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 sv(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new y(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function av(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;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0?null:{pid:r,token:o}}async function bd(e){try{return av(await Qe.readFile(Cs.join(e,hd),"utf8"))}catch{return null}}function cv(e){try{return process.kill(e,0),!0}catch(t){return!Is(t,"ESRCH")}}async function Os(e){try{return await Qe.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function ud(e,t){let n=await bd(e);n===null||n.token!==t||await Os(e)}async function fd(e){try{await Qe.mkdir(e)}catch(n){return Is(n,"EEXIST"),null}let t={pid:process.pid,token:Vw()};try{await Qe.writeFile(Cs.join(e,hd),`${JSON.stringify(t)}
|
|
28
|
-
`,"utf8")}catch{return await Os(e),null}return t}async function lv(e){let t;try{let r=await Qe.stat(e);if(t=Date.now()-r.mtimeMs,t<=tv)return!1}catch(r){return te(r)}let n=await bd(e);return n!==null&&cv(n.pid)&&t<=nv?!1:Os(e)}async function dv(e,t){let n=`${e}${ev}`,r=await fd(n);if(r!==null)return async()=>ud(n,r.token);if(!await lv(n))return null;let o=await fd(n);return o===null?null:async()=>ud(n,o.token)}async function uv(e){let t=await dv(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await pd(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!gd(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(sv(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=Qw)throw yd(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await _d(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 m=iv(a.result);if(m)return async()=>{await Promise.resolve(m()),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}let c=Qc(e,t),l=rv(s),d=Date.now(),u=0,f=Xw;for(;;)try{return await Kw(c,t,r,n),async()=>{await _d(c,"lock:release"),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}catch(m){if(!Is(m,"EEXIST"))throw new y(`Failed to acquire lock for ${t}: ${We(m)}`,h.GENERIC_FAILURE);let _=await pd(c);if(gd(_.info,n)){let b=await uv({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 g=Date.now()-d;if(l===0||g>=l)throw yd(t,_.info,l===0?0:g);await ov(Math.min(f,l-g)),f=Math.min(f*2,Jw)}}(function(){try{var e=typeof window<"u"?window:typeof 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 pe="_workspace";function uo(e){return jn.join(e,"history",`${pe}.jsonl`)}function fv(e,t=e.length){let n=Ln();for(let r of e.slice(0,t))n=cn(n,r.patch).document;return Mn(n)}function pv(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function mv(e){throw new y(`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 _v(e,t){let n=jn.resolve(t),r=jn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||jn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Rs(e){let t=await dt(uo(e),pe),n=Pt(t);n.ok||mv(n.errors);let r=pv(t.length===0?si:fv(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=_v(e,jn.resolve(e,c));if(l=await X(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(D(u)===D(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 gv={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},wd=120;function Ns(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Ed(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var hv=Ed(gv),vd=new WeakMap;function yv(e){let t=vd.get(e);if(t)return t;let n=Ed(e);return vd.set(e,n),n}function kd(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return wd;if(t){let o=yv(t).get(n);if(Ns(o))return Math.floor(o)}let r=hv.get(n);return Ns(r)?Math.floor(r):wd}function Td(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||!Ns(r)||(t[o]=Math.floor(r))}return t}import{stat as bv}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 fo=new Map;function Sd(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function wv(e){try{let t=await bv(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function _t(e){let t=Sd(e),n=await Promise.all(t.map(r=>wv(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Un(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 Ad(e){return fo.get(e)}function po(e,t){let n=Sd(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));fo.set(e,{tracked_paths:n,signatures:r,value:t.value})}function jt(e){if(e){fo.delete(e);return}fo.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 Id=Symbol("pm.settings.persist_source"),Ev=128,kv=new Set(["off","advisory","strict"]);function xd(e){return structuredClone(oi[e])}function Tv(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:ne.governance.preset}function Sv(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),kv.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 Ut(e){let t=e.governance??{},n=Tv(t.preset),r=Sv(t);if(n==="custom"){let s=xd("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=xd(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Od(){return structuredClone(ne)}function Av(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:ne.search.mutation_refresh_policy}function xv(e){return typeof e=="boolean"?e:ne.search.query_expansion.enabled}function Cv(e){return typeof e!="string"?ne.search.query_expansion.provider:e.trim()}function Iv(e){return typeof e=="boolean"?e:ne.search.rerank.enabled}function Ov(e){return typeof e!="string"?ne.search.rerank.model:e.trim()}function Rv(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:ne.search.rerank.top_k}function Nv(e){if(typeof e!="string")return ne.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,Ev);return n.length>0?n:ne.vector_store.collection_name}function Ds(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Dv(e,t){let n=e.schema,r=Ds(n?.statuses),o=Ds(n?.fields),i=Ds(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:go(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:go(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 Rd(e,t){Object.defineProperty(e,Id,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Pv(e){let t=e[Id];if(!(!t||typeof t!="object"))return t}function _o(e){let t=structuredClone(e.settings),n=Pv(e.settings);return n&&Rd(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function Lv(e,t,n){let r=st(t);return[n,ge(e,r.files.types,fe.types),ge(e,r.files.statuses,fe.statuses),ge(e,r.files.fields,fe.fields),ge(e,r.files.workflows,fe.workflows)]}async function Mv(e,t,n){let r=await _t(t);po(e,{tracked_paths:t,signatures:r,value:_o(n)})}async function Fv(e,t,n){try{await Mv(e,t,n)}catch{jt(e)}}function Cd(e,t){return e.find(n=>n.path===t)}function $v(e,t,n){for(let r of n){let o=Cd(e,r),i=Cd(t,r);if(!o||!i||!Un([o],[i]))return!1}return!0}async function Ps(e,t,n,r,o){try{let i=await _t(t);if(!$v(r,i,o)){jt(e);return}po(e,{tracked_paths:t,signatures:i,value:_o(n)})}catch{jt(e)}}function zn(e){return{settings:Od(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function jv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Uv(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function zv(e){let t=ne.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:Uv(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 qv(e){return e==="off"||e==="warn"||e==="enforce"?e:ne.extensions.policy.mode}function Bv(e){return e==="off"||e==="warn"||e==="enforce"?e:ne.extensions.policy.trust_mode}function Nd(e){return e==="none"||e==="restricted"||e==="strict"?e:ne.extensions.policy.default_sandbox_profile}function Gv(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=Nd(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 Vv(e){let t=new Map;for(let n of e??[]){let r=Gv(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Ls(e){return e==="block"||e==="warn"?e:void 0}function Hv(e){if(typeof e=="string")return Ls(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Ls(e.global),n=Ls(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function ve(e,t){return je(e?.[t]??ne.extensions.policy[t])}function Wv(e){let t=Hv(e?.pm_max_version_exceeded_mode);return{mode:qv(e?.mode),trust_mode:Bv(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ve(e,"trusted_extensions"),default_sandbox_profile:Nd(e?.default_sandbox_profile),allowed_extensions:ve(e,"allowed_extensions"),blocked_extensions:ve(e,"blocked_extensions"),allowed_capabilities:ve(e,"allowed_capabilities"),blocked_capabilities:ve(e,"blocked_capabilities"),allowed_surfaces:ve(e,"allowed_surfaces"),blocked_surfaces:ve(e,"blocked_surfaces"),allowed_commands:ve(e,"allowed_commands"),blocked_commands:ve(e,"blocked_commands"),allowed_actions:ve(e,"allowed_actions"),blocked_actions:ve(e,"blocked_actions"),allowed_services:ve(e,"allowed_services"),blocked_services:ve(e,"blocked_services"),extension_overrides:Vv(e?.extension_overrides??ne.extensions.policy.extension_overrides)}}function Kv(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 mo(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Yv(e){return Array.isArray(e)?e:[]}function Xv(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Kv(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:mo(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:mo(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:mo(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:mo(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Td(e.validation?.estimate_defaults_by_type)}}function Jv(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 Zv(e,t){return{...t.search,...e.search,mutation_refresh_policy:Av(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:xv(e.search?.query_expansion?.enabled),provider:Cv(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Iv(e.search?.rerank?.enabled),model:Ov(e.search?.rerank?.model),top_k:Rv(e.search?.rerank?.top_k)}}}function Qv(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Nv(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function eE(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function tE(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 nE(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function go(e){let t=(e??[]).map(r=>Lr(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 rE(e){let t=Od(),n=Ut({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:eE(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:Xv(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:Jv(e,t),agent_guidance:zv(e.agent_guidance??t.agent_guidance),item_types:{definitions:go(e.item_types?.definitions)},schema:st(e.schema??t.schema),context:tE(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:Wv(e.extensions.policy??t.extensions.policy)},search:Zv(e,t),providers:nE(e,t),vector_store:Qv(e,t)}}async function qn(e){let t=ye(e),n=[t];await Le({path:t,scope:"project"});let r=Ad(e);if(r){let l=await _t(r.tracked_paths);if(Un(l,r.signatures))return _o(r.value)}let o=await _t([t]),i;try{i=await X(t)}catch{return zn("settings_read_fs_error")}if(i===null){let l=zn();return await Ps(e,[t],l,o,[t]),l}let s=await _t([t]);if(!Un(o,s))return jt(e),qn(e);let a;try{a=JSON.parse(i)}catch{let l=zn("settings_read_invalid_json");return await Ps(e,[t],l,s,[t]),l}let c=ld(a);if(!c.success){let l=zn("settings_read_invalid_schema");return await Ps(e,[t],l,s,[t]),l}try{let l=rE(c.data),d=Lv(e,l.schema,t);n=d;let u=await _t(d),f=await Ac(e,l.schema),m=await xc(e,l.schema),_=await _t(d),g={...l,item_types:{definitions:go([...l.item_types.definitions,...Yv(m.type_definitions_from_file)])},schema:m.schema};Rd(g,Dv(c.data,g));let b={settings:g,metadata:{has_explicit_item_format:jv(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}`),...m.warnings]};return f.created_paths.length===0?Un(u,_)?po(e,{tracked_paths:d,signatures:_,value:_o(b)}):jt(e):jt(e),b}catch{let l=zn("settings_read_merge_failed");return await Fv(e,n,l),l}}async function Z(e){return(await qn(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]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var Fs=["item","history","relationship","json"];function aE(e){let t=e.trim().toLowerCase();if(Fs.includes(t))return t;throw new y(`Unknown merge artifact "${e}". Supported values: ${Fs.join(", ")}.`,h.USAGE)}function cE(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new y(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,h.USAGE)}async function Ms(e,t){try{return await oE(e,"utf8")}catch{throw new y(`Cannot read merge ${t} file at ${e}.`,h.NOT_FOUND)}}async function lE(e){let t=oe(process.cwd(),e.path);return await q(ye(t))?Z(t):null}function dE(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function uE(e,t){let n=aE(e.artifact),r=cE(e.prefer),o=sE.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Ms(e.basePath,"base"),Ms(e.oursPath,"ours"),Ms(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let m=bs(i,s,a);c=m.merged,u.history={strategy:m.strategy,common_entries:m.common_entries,entries_from_ours:m.entries_from_ours,entries_from_theirs:m.entries_from_theirs,entries_total:m.entries_total,reanchored:m.reanchored}}else if(n==="relationship"){let m=ws(i,s,a);c=m.merged,u.relationship={strategy:m.strategy,common_entries:m.common_entries,entries_from_ours:m.entries_from_ours,entries_from_theirs:m.entries_from_theirs,entries_total:m.entries_total,reanchored:m.reanchored}}else if(n==="item"){let m=await lE(t),_=vs(i,s,a,{format:dE(e.itemPath??o,m),schema:m?.schema,extensionFieldNames:Ze(G()),preferred:r,conflictResolution:"stable_value_order"});c=_.merged,d.push(..._.conflict_fields),u.item={fields_from_theirs:_.fields_from_theirs,union_fields:_.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0&&(l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:_.fields_from_theirs,unionFields:_.union_fields,decisions:_.conflict_decisions})}else{let m=Es(i,s,a,{preferred:r});c=m.merged,d.push(...m.conflict_paths),u.json={paths_from_theirs:m.paths_from_theirs}}if(await iE(o,c,"utf8"),l!==void 0){let m=await cd(l);m!==null&&(u.receipt=Mt(m))}let f=[];if(d.length>0){let m=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. ${m} 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:z()}}import js from"node:fs/promises";import ho 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 gt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Us(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 yo(e){return new y(`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 $s(e){return new y(`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 fE(e){let t=ho.resolve(e),n=ho.parse(t).root,r=ho.dirname(t);for(;r!==n;){let o;try{o=await js.stat(r)}catch(i){if(gt(i,"ENOTDIR"))throw yo(e);if(!gt(i,"ENOENT"))throw i;r=ho.dirname(r);continue}if(!o.isDirectory())throw yo(e);return}}async function Bn(e){let t;try{t=await js.stat(e)}catch(n){throw gt(n,"ENOENT")?(await fE(e),new y(`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:Us(e)})):gt(n,"ENOTDIR")?yo(e):gt(n,"EACCES")||gt(n,"EPERM")?$s(e):n}if(!t.isDirectory())throw yo(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw $s(e);try{await(await js.opendir(e)).close()}catch(n){throw gt(n,"EACCES")||gt(n,"EPERM")?$s(e):n}}async function xe(e){if(await Bn(e),!await q(ye(e)))throw new y(`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:Us(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 wo,realpath as zs,writeFile as gE}from"node:fs/promises";import{execFile as hE}from"node:child_process";import Y from"node:path";import{promisify as yE}from"node:util";import pE 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 Dd=["runtime/","search/","locks/","transactions/","checkpoints/"];function Pd(e){let t=e.replaceAll("\\","/");return pE.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 mE="PM_SOURCE_CONTEXT_ACCESS",_E="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Ld(e){let t=e[mE],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[_E]?.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 qs=yE(hE),Gn="# pm-cli:merge-drivers:start",Bs="# pm-cli:merge-drivers:end",zt="# pm-cli:merge-drivers:v2:start",bo="# pm-cli:merge-drivers:v2:end",bE="merge-fence";function Md(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function jd(){let e=en(import.meta.url,["../../.."]);return`${Md(process.execPath)} ${Md(Y.join(e,"dist","cli.js"))}`}var Ud=[{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 zd(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Ld(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=oe(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:Y.resolve(r),workspace_start:Y.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?oe(e.cwd,".agents/pm"):oe(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function dn(e){try{let{stdout:t}=await qs("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await zs(t.trim())}catch{return null}}async function qd(e){let t=await dn(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Gs(e,t){return Y.relative(e,t).replaceAll("\\","/")}function Ve(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Fd(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 wE(e,t){let n=Fd(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=Fd(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(Y.basename(n.value))||Y.basename(r.value)!=="cli.js"||Y.basename(Y.dirname(r.value))!=="dist"||!await q(n.value)||!await q(r.value))return!1;try{let o=Y.dirname(Y.dirname(r.value)),i=JSON.parse(await wo(Y.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 vo(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ve(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ve(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${Ve(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${Ve(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ve(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ve(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ve(`${n}settings.json`)} merge=pm-json`),r.push(`${Ve(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ve(`${n}extensions/**`)} -merge`),r.push(`${Ve(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function $d(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 Bd(e,t,n){let r=Y.join(e,".gitattributes"),o="";try{o=await wo(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&te(l)))throw l}let i=[zt,...t,bo].join(`
|
|
29
|
-
`),a=$d($d(o,zt,bo),Gn,Bs).trimEnd(),c=`${a.length>0?`${a}
|
|
21
|
+
`}function Iw(e){return e.map((t,n)=>({...t,sequence:n+1}))}function As(e,t,n){ws(e,"base");let r=ws(t,"ours"),o=ws(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:po(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:po(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:po(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 b=pe(f.timestamp,p.timestamp);if(b!==0)return b}else{if(f.timestamp===void 0&&p.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let _=c.has(f.eventId),g=c.has(p.eventId);return _!==g?Number(g)-Number(_):0}),u=Iw([...r.slice(0,s),...d]);return{merged:po(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var cd=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],ld=["updated_at"];function Ft(e,t){return O(e??null)===O(t??null)}function Ow(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(d=>O(d))),i=r(t),s=new Set(i.map(d=>O(d))),a=r(n),c=new Set(a.map(d=>O(d))),l=i.filter(d=>{let u=O(d);return!o.has(u)||c.has(u)});for(let d of a){let u=O(d);!s.has(u)&&!o.has(u)&&l.push(d)}return l}function zn(e){if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let{provenance:t,...n}=e;return O(n)}function Rw(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 Nw(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(zn)),i=r(t),s=new Set(i.map(zn)),a=r(n),c=new Set(a.map(zn)),l=i.filter(d=>{let u=zn(d);return!o.has(u)||c.has(u)});for(let d of a){let u=zn(d);!s.has(u)&&!o.has(u)&&l.push(Rw(d))}return l}function Dw(e,t){return pe(String(e),String(t))>=0?e:t}function dd(e,t,n,r){return Ft(t,n)?{value:t,from_theirs:!1,conflict:!1}:Ft(e,t)?{value:n,from_theirs:!0,conflict:!1}:Ft(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function ud(e,t,n,r,o){let i=dd(e,t,n,r);if(!i.conflict||o==="preferred_side")return i;let s=O(n).localeCompare(O(t))<0;return{value:s?n:t,from_theirs:s,conflict:!0}}function vs(e){return{...e.metadata}}function Es(e,t,n){try{return be(xe(e,n),n)}catch(r){throw new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,h.GENERIC_FAILURE)}}function Pw(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?Nw(e.baseValue,e.oursValue,e.theirsValue):Ow(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Ft(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Lw(e){let t=ud(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);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:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function Mw(e,t,n,r,o){let i=new Set(cd),s=new Set(ld),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,d)=>l.localeCompare(d)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let l of a){let d=e[l],u=t[l],f=n[l];if(!Pw({field:l,baseValue:d,oursValue:u,theirsValue:f,unionFieldSet:i,accumulator:c})){if(s.has(l)){c.merged[l]=Dw(u,f);continue}Lw({field:l,baseValue:d,oursValue:u,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function xs(e,t,n,r={}){let o=r.preferred??"ours",i=r.conflictResolution??"preferred_side",s=e.trim().length>0,a=Es(t,"ours",r),c=Es(n,"theirs",r),l=s?Es(e,"base",r):a,d=s?vs(l):{},u=vs(a),f=vs(c),{merged:p,conflictFields:_,fieldsFromTheirs:g,unionFields:b,conflictDecisions:T}=Mw(d,u,f,o,i),k=ud(s?l.body:"",a.body,c.body,o,i);return k.conflict?(_.push("body"),T.push({field:"body",base:s?l.body:"",ours:a.body,theirs:c.body,retained:k.value,discarded:k.from_theirs?a.body:c.body})):k.from_theirs&&g.push("body"),{merged:It({metadata:p,body:k.value},r),conflict_fields:_,fields_from_theirs:g,union_fields:b,conflict_decisions:T,requested_preference:o,conflict_resolution:i}}function ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ts(e,t){let n=Le(e);if(n)throw new y(`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 y(`JSON merge input (${t}) is not valid JSON.`,h.GENERIC_FAILURE)}}function Fw(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=O(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=O(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 $w(e,t,n,r,o,i,s){if(!ks(t)||!ks(n))return null;let a=ks(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=jw(a,t,n,d,r,u,i,s);f!==void 0&&(c[d]=f)}return c}function fd(e,t,n,r,o,i,s){if(Ft(t,n))return t;let a=Fw(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(o),a.merged;let c=$w(e,t,n,r,o,i,s);if(c!==null)return c;let l=dd(e,t,n,r);return l.conflict?i.push(o):l.from_theirs&&s.push(o),l.value}function jw(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 fd(e[r],t[r],n[r],o,i,s,a);if(c){if(d&&Ft(e[r],t[r])){a.push(i);return}return d?(s.push(i),o==="theirs"?void 0:t[r]):t[r]}if(!(d&&Ft(e[r],n[r])))return d?(s.push(i),o==="theirs"?n[r]:void 0):(a.push(i),n[r])}function Cs(e,t,n,r={}){let o=r.preferred??"ours",i=Ts(e,"base"),s=Ts(t,"ours"),a=Ts(n,"theirs"),c=[],l=[],d=fd(i,s,a,o,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
|
|
22
|
+
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as Gw}from"node:child_process";import{randomUUID as Vw}from"node:crypto";import{readdir as Hw}from"node:fs/promises";import oe from"node:path";import{promisify as Ww}from"node:util";import{constants as pd}from"node:fs";import{lstat as Uw,open as zw}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 qw={lstat:Uw,open:zw};function Bw(e){return e.O_NOFOLLOW??0}async function md(e,t,n=qw){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let o=await n.open(e,pd.O_RDONLY|Bw(pd));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]="5add49c0-25be-5159-abfc-6c7ae9272f6b")}catch{}})();var Kw=Ww(Gw),Yw=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,Xw=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Os=2048,Jw=16*1024*1024,Zw=64,Qw=1e5,ev=new Set(["version","id","item_path","item_id","requested_preference","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","evidence_source"]),tv=new Set(["field","base","ours","theirs","retained","discarded"]);async function Rs(e){try{let{stdout:t}=await Kw("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 bd(e,t){let n=oe.dirname(oe.resolve(e,t));for(let r=0;r<12;r+=1){if(await B(oe.join(n,"settings.json")))return n;let o=oe.dirname(n);if(o===n)break;n=o}return null}function Ns(e){return oe.join(e,"merge-receipts")}function dn(e){return`${e}.json`}function Bn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wd(e,t){return Object.keys(e).every(n=>t.has(n))}function _d(e){return Array.isArray(e)&&e.length<=Os&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function qn(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>Qw||r.depth>Zw)return!1;if(Array.isArray(r.value))for(let o of r.value)t.push({value:o,depth:r.depth+1});else if(Bn(r.value))for(let o of Object.values(r.value))t.push({value:o,depth:r.depth+1})}return!0}function nv(e){return Bn(e)&&wd(e,tv)&&typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&Object.hasOwn(e,"base")&&Object.hasOwn(e,"ours")&&Object.hasOwn(e,"theirs")&&Object.hasOwn(e,"retained")&&Object.hasOwn(e,"discarded")&&qn(e.base)&&qn(e.ours)&&qn(e.theirs)&&qn(e.retained)&&qn(e.discarded)}function rv(e){if(!Bn(e))return!1;let t=Object.entries(e);return t.length<=Os&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function ov(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||oe.posix.isAbsolute(e))return!1;let n=oe.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&oe.posix.basename(n,oe.posix.extname(n))===t}function iv(e){return!wd(e,ev)||e.version!==1?!1:typeof e.id=="string"&&Yw.test(e.id)&&typeof e.item_id=="string"&&Xw.test(e.item_id)&&ov(e.item_path,e.item_id)}function sv(e){return!_d(e.fields_from_theirs)||!_d(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Os||!e.decisions.every(nv)?!1:e.merged_field_hashes===void 0||rv(e.merged_field_hashes)}function av(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order"],r=[void 0,"clone_local","hash_only"],o=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&o.includes(e.evidence_source)}function cv(e){return typeof e.created_at=="string"&&En(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&En(e.reconciled_at))}function lv(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&hd(t.retained)&&hd(t.discarded))}function Ds(e,t){return!Bn(e)||!iv(e)||!sv(e)||!av(e)||!cv(e)?!1:t!=="durable"||lv(e)}async function vd(e){return md(e,Jw)}async function gd(e){let t;try{t=await vd(e.receiptPath)}catch(i){if(kn(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(!Ds(n,e.evidenceSource)||n.id!==e.receiptId||oe.basename(e.receiptPath)!==dn(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:mo(n),content:`${JSON.stringify({...o,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
|
|
23
|
+
`}}function mo(e){return ce(O({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:Ve(e).decisions}))}function dv(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function Ve(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",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Is(t.retained)??ce(O(t.retained)),discarded_hash:Is(t.discarded)??ce(O(t.discarded))}))}}function Is(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 hd(e){return Bn(e)&&Object.keys(e).length===1&&Is(e)!==void 0}async function Ed(e){let t=await Rs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,o=oe.basename(r,oe.extname(r)),i={version:1,id:Vw(),item_path:r.replaceAll("\\","/"),item_id:o,requested_preference:e.preferred,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:q(),value_availability:"clone_local"};await st(t),await $(oe.join(t,dn(i.id)),`${JSON.stringify(i,null,2)}
|
|
24
|
+
`);let s=await bd(e.cwd,i.item_path);if(s!==null){let a=Ns(s),c=Ve(i),l={...i,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await st(a),await $(oe.join(a,dn(i.id)),`${JSON.stringify(l,null,2)}
|
|
25
|
+
`)}return i}async function yd(e,t){if(!await B(e))return{receipts:[],invalid_evidence_count:0};let n;try{n=await Hw(e)}catch{return{receipts:[],invalid_evidence_count:1}}let r=[],o=0;for(let i of n.sort((s,a)=>s.localeCompare(a)))if(i.endsWith(".json"))try{let s=oe.join(e,i),a=await vd(s);if(a===null){o+=1;continue}let c=JSON.parse(a);if(!Ds(c,t)||i!==dn(c.id)){o+=1;continue}let{preferred:l,evidence_source:d,...u}=c,f={...u,requested_preference:c.requested_preference??l??"ours",conflict_resolution:c.conflict_resolution??"preferred_side",evidence_source:t};r.push(f)}catch{o+=1}return{receipts:r,invalid_evidence_count:o}}async function Gn(e,t={}){let n=await Rs(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await yd(n,"clone_local"),o=t.pmRoot??oe.join(e,".agents","pm"),i=await yd(Ns(o),"durable"),s=new Map(i.receipts.map(c=>[c.id,c])),a=0;for(let c of r.receipts){let l=s.get(c.id);if(l!==void 0&&mo(l)!==mo(c)){s.delete(c.id),a+=1;continue}s.set(c.id,l===void 0?c:dv(c,l))}return{receipts:[...s.values()].filter(c=>(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)).sort((c,l)=>c.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+i.invalid_evidence_count+a}}async function kd(e,t={}){return(await Gn(e,t)).receipts}function _o(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 Ps(e,t,n={}){let r=await Rs(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let o=q(),i=oe.join(r,dn(t.id)),s=await bd(e,t.item_path),a=s===null?null:oe.join(Ns(s),dn(t.id)),l=(await Promise.all([gd({receiptPath:i,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o}),...a===null?[]:[gd({receiptPath:a,receiptId:t.id,evidenceSource:"durable",reconciledAt:o})]])).filter(p=>p!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let d=t.evidence_source??"clone_local",u=t.id;if(!Ds(t,d))throw new Error(`Receipt ${u} trusted settlement input failed schema validation.`);let f=mo(t);if(new Set([f,...l.map(p=>p.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let p of l)await $(p.path,p.content)}async function uv(e){let t=await kd(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:q()}}import{readFile as BE,writeFile as GE}from"node:fs/promises";import VE 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 $t=new Set(Te),fv=Object.freeze({get size(){return $t.size},has(e){return $t.has(e)},entries(){return $t.entries()},keys(){return $t.keys()},values(){return $t.values()},forEach(e,t){$t.forEach(n=>e.call(t,n,n,fv))},[Symbol.iterator](){return $t.values()}});function pv(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function mv(e){return typeof e!="string"?null:Pi(e)}function _v(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=mv(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new y(`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 Qe(e){return[..._v(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 se={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:se,L=e=>typeof e=="boolean"?{ok:!0,value:e}:se;function j(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?se:{ok:!0,value:t}}function M(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:se}function S(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return se;let r=[];for(let o of n){let i=e(o);if(!i.ok)return se;r.push(i.value)}return{ok:!0,value:r}}}function Ms(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}:se}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function go(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return se;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return se;n[r]=i.value}return{ok:!0,value:n}}}function R(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return se;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return se;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var gv=R({key:w,values:S(w),required:m(L),aliases:m(S(w)),description:m(w)}),hv=R({command:M("create","update"),option:w,required:m(L),visible:m(L),enabled:m(L)}),yv=R({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(S(w)),required_create_fields:m(S(w)),required_create_repeatables:m(S(w)),options:m(S(gv)),command_option_policies:m(S(hv))}),bv=R({id:w,aliases:m(S(w)),roles:m(S(M(...Er))),description:m(w),order:m(j())}),wv=R({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(S(w)),description:m(w),type:m(M(...Kt)),commands:m(S(M(...kr))),repeatable:m(L),required:m(L),required_on_create:m(L),required_types:m(S(w)),allow_unset:m(L)}),vv=e=>{if(!Array.isArray(e)||e.length!==2)return se;let[t,n]=e;return typeof t!="string"||typeof n!="string"?se:{ok:!0,value:[t,n]}},Ev=R({type:w,allowed_transitions:S(vv)}),kv=m(R({version:m(j({int:!0})),files:m(R({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(S(bv)),fields:m(S(wv)),workflow:m(R({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(S(Ev)),unknown_field_policy:m(M(...Tr))})),Tv=m(R({preset:m(M(...yc)),ownership_enforcement:m(M("none","warn","strict")),create_mode_default:m(M("progressive","strict")),close_validation_default:m(M("off","warn","strict")),require_close_reason:m(L),parent_reference:m(M("warn","strict_error")),metadata_profile:m(M("core","strict","custom")),force_required_for_stale_lock:m(L),create_default_type:m(w),workflow_enforcement:m(M("off","warn","strict")),duplicate_detection_mode:m(M("off","advisory","strict")),duplicate_detection_threshold:m(j({min:0,max:1})),duplicate_detection_limit:m(j({int:!0,min:0,max:20}))})),Sv=R({name:w,disabled:m(L),require_trusted:m(L),require_provenance:m(L),sandbox_profile:m(M("none","restricted","strict")),allowed_capabilities:m(S(w)),blocked_capabilities:m(S(w)),allowed_surfaces:m(S(w)),blocked_surfaces:m(S(w)),allowed_commands:m(S(w)),blocked_commands:m(S(w)),allowed_actions:m(S(w)),blocked_actions:m(S(w)),allowed_services:m(S(w)),blocked_services:m(S(w))}),Ls=M("block","warn"),Av=e=>typeof e=="string"?Ls(e):R({global:m(Ls),project:m(Ls)})(e),xv=m(R({mode:m(M("off","warn","enforce")),trust_mode:m(M("off","warn","enforce")),pm_max_version_exceeded_mode:m(Av),require_provenance:m(L),trusted_extensions:m(S(w)),default_sandbox_profile:m(M("none","restricted","strict")),allowed_extensions:m(S(w)),blocked_extensions:m(S(w)),allowed_capabilities:m(S(w)),blocked_capabilities:m(S(w)),allowed_surfaces:m(S(w)),blocked_surfaces:m(S(w)),allowed_commands:m(S(w)),blocked_commands:m(S(w)),allowed_actions:m(S(w)),blocked_actions:m(S(w)),allowed_services:m(S(w)),blocked_services:m(S(w)),extension_overrides:m(S(Sv))})),jt=Ms(128),Cv=R({harness:Ms(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(S(jt,64)),model_environment_keys:m(S(jt,64)),session_environment_keys:m(S(jt,64)),provenance_environment_keys:m(go(S(jt,64))),provenance_resolvers:m(go(M("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(S(jt,64)),argv_markers:m(S(jt,64)),client_names:m(S(jt,64))}),Iv=R({version:j({int:!0}),id_prefix:w,ids:m(R({token_length:m(j({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(R({probes_enabled:m(L),identity_vocabulary:m(R({version:j({int:!0,positive:!0}),aliases:go(Ms(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:S(Cv)})),mutation_guard:m(R({require_attributed_author:m(L),secret_guard:m(M("off","advise","block")),stale_in_progress_hours:m(j({int:!0,positive:!0}))})),item_format:m(M("toon","json_markdown")),locks:R({ttl_seconds:j({int:!0}),wait_ms:m(j({int:!0,min:0}))}),checkpoints:m(R({retention_days:m(j({int:!0,positive:!0}))})),output:R({default_format:M("toon","json")}),ux:m(R({deprecation_hints:m(L)})),history:m(R({missing_stream:M("auto_create","strict_error"),compact_policy:m(R({enabled:m(L),max_entries:m(j({int:!0,positive:!0})),trigger:m(M("health_warn","auto"))}))})),validation:m(R({sprint_release_format:M("warn","strict_error"),parent_reference:m(M("warn","strict_error")),metadata_profile:m(M("core","strict","custom")),metadata_required_fields:m(S(w)),lifecycle_stale_blocker_reason_patterns:m(S(w)),lifecycle_closure_like_blocked_reason_patterns:m(S(w)),lifecycle_closure_like_resolution_patterns:m(S(w)),lifecycle_closure_like_actual_result_patterns:m(S(w)),estimate_defaults_by_type:m(go(j({int:!0,positive:!0})))})),governance:Tv,workflow:m(R({definition_of_done:S(w)})),testing:m(R({record_results_to_items:L,allow_untrusted_linked_tests:m(L)})),telemetry:m(R({enabled:L,first_run_prompt_completed:m(L),capture_level:m(M("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(j({int:!0,positive:!0}))})),agent_guidance:m(R({prompt_completed:m(L),declined:m(L),declined_at:m(w),template_version:m(j({int:!0,positive:!0})),last_checked_files:m(S(w))})),item_types:m(R({definitions:S(yv)})),schema:kv,context:m(R({default_depth:m(M("brief","standard","deep")),activity_limit:m(j({int:!0,positive:!0})),stale_threshold_days:m(j({int:!0,positive:!0})),sections:m(R({hierarchy:m(L),activity:m(L),progress:m(L),recently_created:m(L),unparented:m(L),blockers:m(L),files:m(L),workload:m(L),staleness:m(L),tests:m(L)}))})),extensions:R({enabled:S(w),disabled:S(w),policy:xv}),search:R({score_threshold:j(),hybrid_semantic_weight:m(j()),max_results:j({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(j()),embedding_batch_size:j({int:!0}),embedding_timeout_ms:m(j({int:!0})),scanner_max_batch_retries:j({int:!0}),provider:m(w),corpus_fields:m(S(w)),mutation_refresh_policy:m(M("cache_only","semantic_configured","semantic_auto")),query_expansion:m(R({enabled:m(L),provider:m(w)})),rerank:m(R({enabled:m(L),model:m(w),top_k:m(j({int:!0,positive:!0}))})),bm25:m(R({k1:m(j()),b:m(j())}))}),providers:R({openai:R({base_url:w,api_key:w,model:w}),ollama:R({base_url:w,model:w})}),vector_store:R({adapter:m(w),collection_name:m(w),qdrant:R({url:w,api_key:w}),lancedb:R({path:w})})});function Td(e){let t=Iv(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Vn from"node:path";import et from"node:fs/promises";import Fs from"node:path";import{randomUUID as Ov}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 Rv(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 Cd(e){try{let t=await et.readFile(e,"utf8");return await Me({path:e,scope:"project"}),Rv(t)}catch(t){return te(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function $s(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Id(e,t){await ve({path:e,scope:"project",op:t})}function Nv(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:q(),ttl_seconds:n}}async function Dv(e,t,n,r){await et.mkdir(Fs.dirname(e),{recursive:!0});let o=await et.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Nv(t,n,r),null,2)}
|
|
26
|
+
`,"utf8")}finally{await o.close()}await Id(e,"lock:create")}async function Od(e,t){try{return await et.unlink(e),await Id(e,t),!0}catch{return!1}}function Rd(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 Pv(e){return e?.owner?` (owner ${e.owner})`:""}var Lv=25,Mv=200,Fv=250,$v=3,jv=".stale-cleanup",Nd="owner.json",Uv=1e4,zv=5*6e4;function Sd(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 qv(e){let t=process.env.PM_LOCK_WAIT_MS,n=Sd(t);if(n!==void 0)return n;let r=Sd(e);return r!==void 0?r:0}function Bv(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function Dd(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new y(`Item ${e} is locked${Pv(t)}${r}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:Fv}})}function Gv(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 Vv(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new y(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function Hv(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;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0?null:{pid:r,token:o}}async function Pd(e){try{return Hv(await et.readFile(Fs.join(e,Nd),"utf8"))}catch{return null}}function Wv(e){try{return process.kill(e,0),!0}catch(t){return!$s(t,"ESRCH")}}async function js(e){try{return await et.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Ad(e,t){let n=await Pd(e);n===null||n.token!==t||await js(e)}async function xd(e){try{await et.mkdir(e)}catch(n){return $s(n,"EEXIST"),null}let t={pid:process.pid,token:Ov()};try{await et.writeFile(Fs.join(e,Nd),`${JSON.stringify(t)}
|
|
27
|
+
`,"utf8")}catch{return await js(e),null}return t}async function Kv(e){let t;try{let r=await et.stat(e);if(t=Date.now()-r.mtimeMs,t<=Uv)return!1}catch(r){return te(r)}let n=await Pd(e);return n!==null&&Wv(n.pid)&&t<=zv?!1:js(e)}async function Yv(e,t){let n=`${e}${jv}`,r=await xd(n);if(r!==null)return async()=>Ad(n,r.token);if(!await Kv(n))return null;let o=await xd(n);return o===null?null:async()=>Ad(n,o.token)}async function Xv(e){let t=await Yv(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await Cd(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!Rd(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Vv(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=$v)throw Dd(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await Od(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function je(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=Gv(a.result);if(p)return async()=>{await Promise.resolve(p()),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}let c=sl(e,t),l=qv(s),d=Date.now(),u=0,f=Lv;for(;;)try{return await Dv(c,t,r,n),async()=>{await Od(c,"lock:release"),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!$s(p,"EEXIST"))throw new y(`Failed to acquire lock for ${t}: ${Ke(p)}`,h.GENERIC_FAILURE);let _=await Cd(c);if(Rd(_.info,n)){let b=await Xv({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 g=Date.now()-d;if(l===0||g>=l)throw Dd(t,_.info,l===0?0:g);await Bv(Math.min(f,l-g)),f=Math.min(f*2,Mv)}}(function(){try{var e=typeof window<"u"?window:typeof 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 _e="_workspace";function ho(e){return Vn.join(e,"history",`${_e}.jsonl`)}function Jv(e,t=e.length){let n=$n();for(let r of e.slice(0,t))n=ln(n,r.patch).document;return jn(n)}function Zv(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Qv(e){throw new y(`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 eE(e,t){let n=Vn.resolve(t),r=Vn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Vn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Us(e){let t=await ut(ho(e),_e),n=Mt(t);n.ok||Qv(n.errors);let r=Zv(t.length===0?fi:Jv(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=eE(e,Vn.resolve(e,c));if(l=await X(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(O(u)===O(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 tE={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Ld=120;function zs(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Fd(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var nE=Fd(tE),Md=new WeakMap;function rE(e){let t=Md.get(e);if(t)return t;let n=Fd(e);return Md.set(e,n),n}function $d(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Ld;if(t){let o=rE(t).get(n);if(zs(o))return Math.floor(o)}let r=nE.get(n);return zs(r)?Math.floor(r):Ld}function jd(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||!zs(r)||(t[o]=Math.floor(r))}return t}import{stat as oE}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 yo=new Map;function Ud(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function iE(e){try{let t=await oE(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function gt(e){let t=Ud(e),n=await Promise.all(t.map(r=>iE(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Hn(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 yo.get(e)}function bo(e,t){let n=Ud(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));yo.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Ut(e){if(e){yo.delete(e);return}yo.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 Gd=Symbol("pm.settings.persist_source"),aE=128,cE=new Set(["off","advisory","strict"]);function qd(e){return structuredClone(di[e])}function lE(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:re.governance.preset}function dE(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),cE.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 zt(e){let t=e.governance??{},n=lE(t.preset),r=dE(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 Vd(){return structuredClone(re)}function uE(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:re.search.mutation_refresh_policy}function fE(e){return typeof e=="boolean"?e:re.search.query_expansion.enabled}function pE(e){return typeof e!="string"?re.search.query_expansion.provider:e.trim()}function mE(e){return typeof e=="boolean"?e:re.search.rerank.enabled}function _E(e){return typeof e!="string"?re.search.rerank.model:e.trim()}function gE(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:re.search.rerank.top_k}function hE(e){if(typeof e!="string")return re.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,aE);return n.length>0?n:re.vector_store.collection_name}function qs(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function yE(e,t){let n=e.schema,r=qs(n?.statuses),o=qs(n?.fields),i=qs(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Eo(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:Eo(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 Hd(e,t){Object.defineProperty(e,Gd,{value:t,writable:!0,configurable:!0,enumerable:!1})}function bE(e){let t=e[Gd];if(!(!t||typeof t!="object"))return t}function vo(e){let t=structuredClone(e.settings),n=bE(e.settings);return n&&Hd(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function wE(e,t,n){let r=at(t);return[n,ye(e,r.files.types,me.types),ye(e,r.files.statuses,me.statuses),ye(e,r.files.fields,me.fields),ye(e,r.files.workflows,me.workflows)]}async function vE(e,t,n){let r=await gt(t);bo(e,{tracked_paths:t,signatures:r,value:vo(n)})}async function EE(e,t,n){try{await vE(e,t,n)}catch{Ut(e)}}function Bd(e,t){return e.find(n=>n.path===t)}function kE(e,t,n){for(let r of n){let o=Bd(e,r),i=Bd(t,r);if(!o||!i||!Hn([o],[i]))return!1}return!0}async function Bs(e,t,n,r,o){try{let i=await gt(t);if(!kE(r,i,o)){Ut(e);return}bo(e,{tracked_paths:t,signatures:i,value:vo(n)})}catch{Ut(e)}}function Wn(e){return{settings:Vd(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function TE(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function SE(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function AE(e){let t=re.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:SE(e?.last_checked_files??t.last_checked_files)}}function Ue(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function xE(e){return e==="off"||e==="warn"||e==="enforce"?e:re.extensions.policy.mode}function CE(e){return e==="off"||e==="warn"||e==="enforce"?e:re.extensions.policy.trust_mode}function Wd(e){return e==="none"||e==="restricted"||e==="strict"?e:re.extensions.policy.default_sandbox_profile}function IE(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=Wd(e.sandbox_profile));let r=Ue(e.allowed_capabilities),o=Ue(e.blocked_capabilities),i=Ue(e.allowed_surfaces),s=Ue(e.blocked_surfaces),a=Ue(e.allowed_commands),c=Ue(e.blocked_commands),l=Ue(e.allowed_actions),d=Ue(e.blocked_actions),u=Ue(e.allowed_services),f=Ue(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 OE(e){let t=new Map;for(let n of e??[]){let r=IE(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Gs(e){return e==="block"||e==="warn"?e:void 0}function RE(e){if(typeof e=="string")return Gs(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Gs(e.global),n=Gs(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function Ee(e,t){return Ue(e?.[t]??re.extensions.policy[t])}function NE(e){let t=RE(e?.pm_max_version_exceeded_mode);return{mode:xE(e?.mode),trust_mode:CE(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:Ee(e,"trusted_extensions"),default_sandbox_profile:Wd(e?.default_sandbox_profile),allowed_extensions:Ee(e,"allowed_extensions"),blocked_extensions:Ee(e,"blocked_extensions"),allowed_capabilities:Ee(e,"allowed_capabilities"),blocked_capabilities:Ee(e,"blocked_capabilities"),allowed_surfaces:Ee(e,"allowed_surfaces"),blocked_surfaces:Ee(e,"blocked_surfaces"),allowed_commands:Ee(e,"allowed_commands"),blocked_commands:Ee(e,"blocked_commands"),allowed_actions:Ee(e,"allowed_actions"),blocked_actions:Ee(e,"blocked_actions"),allowed_services:Ee(e,"allowed_services"),blocked_services:Ee(e,"blocked_services"),extension_overrides:OE(e?.extension_overrides??re.extensions.policy.extension_overrides)}}function DE(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 wo(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function PE(e){return Array.isArray(e)?e:[]}function LE(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:DE(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:wo(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:wo(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:wo(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:wo(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:jd(e.validation?.estimate_defaults_by_type)}}function ME(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 FE(e,t){return{...t.search,...e.search,mutation_refresh_policy:uE(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:fE(e.search?.query_expansion?.enabled),provider:pE(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:mE(e.search?.rerank?.enabled),model:_E(e.search?.rerank?.model),top_k:gE(e.search?.rerank?.top_k)}}}function $E(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:hE(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function jE(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function UE(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 zE(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Eo(e){let t=(e??[]).map(r=>qr(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 qE(e){let t=Vd(),n=zt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:jE(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:LE(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:ME(e,t),agent_guidance:AE(e.agent_guidance??t.agent_guidance),item_types:{definitions:Eo(e.item_types?.definitions)},schema:at(e.schema??t.schema),context:UE(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:NE(e.extensions.policy??t.extensions.policy)},search:FE(e,t),providers:zE(e,t),vector_store:$E(e,t)}}async function Kn(e){let t=we(e),n=[t];await Me({path:t,scope:"project"});let r=zd(e);if(r){let l=await gt(r.tracked_paths);if(Hn(l,r.signatures))return vo(r.value)}let o=await gt([t]),i;try{i=await X(t)}catch{return Wn("settings_read_fs_error")}if(i===null){let l=Wn();return await Bs(e,[t],l,o,[t]),l}let s=await gt([t]);if(!Hn(o,s))return Ut(e),Kn(e);let a;try{a=JSON.parse(i)}catch{let l=Wn("settings_read_invalid_json");return await Bs(e,[t],l,s,[t]),l}let c=Td(a);if(!c.success){let l=Wn("settings_read_invalid_schema");return await Bs(e,[t],l,s,[t]),l}try{let l=qE(c.data),d=wE(e,l.schema,t);n=d;let u=await gt(d),f=await Dc(e,l.schema),p=await Pc(e,l.schema),_=await gt(d),g={...l,item_types:{definitions:Eo([...l.item_types.definitions,...PE(p.type_definitions_from_file)])},schema:p.schema};Hd(g,yE(c.data,g));let b={settings:g,metadata:{has_explicit_item_format:TE(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(T=>`runtime_schema_bootstrap_created:${T}`),...p.warnings]};return f.created_paths.length===0?Hn(u,_)?bo(e,{tracked_paths:d,signatures:_,value:vo(b)}):Ut(e):Ut(e),b}catch{let l=Wn("settings_read_merge_failed");return await EE(e,n,l),l}}async function Z(e){return(await Kn(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 Hs=["item","history","relationship","json"];function HE(e){let t=e.trim().toLowerCase();if(Hs.includes(t))return t;throw new y(`Unknown merge artifact "${e}". Supported values: ${Hs.join(", ")}.`,h.USAGE)}function WE(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new y(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,h.USAGE)}async function Vs(e,t){try{return await BE(e,"utf8")}catch{throw new y(`Cannot read merge ${t} file at ${e}.`,h.NOT_FOUND)}}async function KE(e){let t=ne(process.cwd(),e.path);return await B(we(t))?Z(t):null}function YE(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function XE(e,t){let n=HE(e.artifact),r=WE(e.prefer),o=VE.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Vs(e.basePath,"base"),Vs(e.oursPath,"ours"),Vs(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=Ss(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=As(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 KE(t),_=YE(e.itemPath??o,p),g=Qe(V()),b=xs(i,s,a,{format:_,schema:p?.schema,extensionFieldNames:g,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 T=xe(c,{format:_,schema:p?.schema,extensionFieldNames:g}),k=T.metadata,I=[...new Set([...b.fields_from_theirs,...b.union_fields,...b.conflict_decisions.map(x=>x.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(I.map(x=>[x,ce(O(x==="body"?T.body:k[x]))])),decisions:b.conflict_decisions}}}else{let p=Cs(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await GE(o,c,"utf8"),l!==void 0){let p=await Ed(l);p!==null&&(u.receipt=Ve(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 Ks from"node:fs/promises";import ko 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 ht(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ys(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 To(e){return new y(`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 Ws(e){return new y(`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 JE(e){let t=ko.resolve(e),n=ko.parse(t).root,r=ko.dirname(t);for(;r!==n;){let o;try{o=await Ks.stat(r)}catch(i){if(ht(i,"ENOTDIR"))throw To(e);if(!ht(i,"ENOENT"))throw i;r=ko.dirname(r);continue}if(!o.isDirectory())throw To(e);return}}async function Yn(e){let t;try{t=await Ks.stat(e)}catch(n){throw ht(n,"ENOENT")?(await JE(e),new y(`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:Ys(e)})):ht(n,"ENOTDIR")?To(e):ht(n,"EACCES")||ht(n,"EPERM")?Ws(e):n}if(!t.isDirectory())throw To(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Ws(e);try{await(await Ks.opendir(e)).close()}catch(n){throw ht(n,"EACCES")||ht(n,"EPERM")?Ws(e):n}}async function Ie(e){if(await Yn(e),!await B(we(e)))throw new y(`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:Ys(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 Ao,realpath as Xs,writeFile as tk}from"node:fs/promises";import{execFile as nk}from"node:child_process";import K from"node:path";import{promisify as rk}from"node:util";import ZE 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 Kd=["runtime/","search/","locks/","transactions/","checkpoints/"];function Yd(e){let t=e.replaceAll("\\","/");return ZE.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 QE="PM_SOURCE_CONTEXT_ACCESS",ek="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Xd(e){let t=e[QE],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[ek]?.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 Js=rk(nk),Xn="# pm-cli:merge-drivers:start",Zs="# pm-cli:merge-drivers:end",qt="# pm-cli:merge-drivers:v2:start",So="# pm-cli:merge-drivers:v2:end",ok="merge-fence";function Jd(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function eu(){let e=tn(import.meta.url,["../../.."]);return`${Jd(process.execPath)} ${Jd(K.join(e,"dist","cli.js"))}`}var tu=[{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 nu(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Xd(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=ne(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:K.resolve(r),workspace_start:K.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?ne(e.cwd,".agents/pm"):ne(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function yt(e){try{let{stdout:t}=await Js("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Xs(t.trim())}catch{return null}}async function ru(e){let t=await yt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Qs(e,t){return K.relative(e,t).replaceAll("\\","/")}function He(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Zd(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 ik(e,t){let n=Zd(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=Zd(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(K.basename(n.value))||K.basename(r.value)!=="cli.js"||K.basename(K.dirname(r.value))!=="dist"||!await B(n.value)||!await B(r.value))return!1;try{let o=K.dirname(K.dirname(r.value)),i=JSON.parse(await Ao(K.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 xo(e,t){let n=e.length>0?`${e}/`:"",r=[`${He(`${n}**/*.toon`)} merge=pm-item-toon`,`${He(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${He(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${He(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${He(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${He(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${He(`${n}settings.json`)} merge=pm-json`),r.push(`${He(`${n}**/*.json`)} merge=pm-json`),r.push(`${He(`${n}extensions/**`)} -merge`),r.push(`${He(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Qd(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 ou(e,t,n){let r=K.join(e,".gitattributes"),o="";try{o=await Ao(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&te(l)))throw l}let i=[qt,...t,So].join(`
|
|
28
|
+
`),a=Qd(Qd(o,qt,So),Xn,Zs).trimEnd(),c=`${a.length>0?`${a}
|
|
30
29
|
|
|
31
30
|
`:""}${i}
|
|
32
|
-
`;return c===o?{path:r,changed:!1}:(n||await
|
|
33
|
-
`).map(k=>k.trim()).filter(k=>k.length>0):[],
|
|
31
|
+
`;return c===o?{path:r,changed:!1}:(n||await tk(r,c,"utf8"),{path:r,changed:!0})}function Co(e){let t=le(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ea(e,t){let n=K.resolve(e),r=null,o="",i=n;for(let k=0;k<8;k+=1){let I=K.join(i,".gitattributes");try{let v=await Ao(I,"utf8");if(v.includes(qt)||v.includes(Xn)){r=i,o=v;break}}catch{}let x=K.dirname(i);if(x===i)break;i=x}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=K.join(r,".gitattributes"),a=o.includes(qt),c=a?qt:Xn,l=a?So:Zs,d=o.indexOf(c),u=o.indexOf(l),f=u>d?o.slice(d+c.length,u).split(`
|
|
32
|
+
`).map(k=>k.trim()).filter(k=>k.length>0):[],p=xo(Qs(r,n),t),_=new Set(f),g=new Set(p),b=p.filter(k=>!_.has(k)),T=f.filter(k=>!g.has(k));return{status:b.length>0||T.length>0?"drift":"ok",path:s,missing_patterns:b,stale_patterns:T,schema_scope:"project"}}async function ta(e){let t=eu(),n=[],r=[];for(let o of tu){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 Js("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await ik(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 sk(e){let t;try{t=await ru(K.resolve(e))}catch{return{status:"no_git"}}let n=Qs(t,K.resolve(e)),r=await Z(e),o=Fe(void 0,r.author_default),i=await je(e,ok,r.locks.ttl_seconds,o,!1,zt(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=K.join(t,".gitattributes"),a;try{a=await Ao(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&te(u))return{status:"not_installed",path:s};throw u}if(!a.includes(qt)&&!a.includes(Xn))return{status:"not_installed",path:s};let c=await Z(e),l=Co(c),d=await ou(t,xo(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function ak(e,t){let n=nu({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Ie(r);let o=await ru(n.workspace_start);return ck({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function ck(e){let t=K.resolve(e.pmRoot),n=K.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([Xs(t),Xs(n)])}catch(p){throw new y(`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=Qs(i,o);if(Yd(s))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let a=await Z(o),c=Co(a),l=xo(s,c),d=[],u=eu();for(let p of tu)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 Js("git",["config","--local",p.key,p.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`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 ou(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 Bu}from"node:fs/promises";import PT from"node:path";import Gu 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 iu(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Jn(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?iu(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?iu(t):"root"}import bT from"node:fs/promises";import nr from"node:fs/promises";import aT from"node:path";import lk from"node:fs/promises";import dk 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 uk(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function fk(e,t){return new y(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,h.NOT_FOUND)}async function pk(e,t){return await st(dk.dirname(e)),await(await lk.open(e,"a")).close(),ve({path:e,scope:"project",op:`${t}:history:auto_create`})}async function na(e){return su({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function su(e){let t=uk(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 fk(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 mk(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 un(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function bt(e,t){let n=mk(t),r=un(e);return r.startsWith(n)?r:`${n}${r}`}import de from"node:fs/promises";import G from"node:path";import{createHash as Ek,randomUUID as hu}from"node:crypto";import Bt from"node:fs/promises";import au from"node:path";import{randomUUID as _k}from"node:crypto";import{createRequire as gk}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 hk="metadata-query-index.sqlite",cu="4";function yk(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Io;function bk(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?yk(t):null}function lu(){return Io!==void 0||(Io=bk(process.versions.node,gk(import.meta.url))),Io}function ra(e){return au.join(e,"runtime",hk)}function wk(e){e.exec(`
|
|
34
33
|
PRAGMA foreign_keys = ON;
|
|
35
34
|
PRAGMA journal_mode = OFF;
|
|
36
35
|
PRAGMA synchronous = OFF;
|
|
@@ -85,7 +84,7 @@ ${i}
|
|
|
85
84
|
tags,
|
|
86
85
|
tokenize = 'unicode61'
|
|
87
86
|
);
|
|
88
|
-
`)}function
|
|
87
|
+
`)}function Oo(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function du(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
|
|
89
88
|
id, relative_path, metadata_json, status, type, priority,
|
|
90
89
|
updated_at, created_at, parent, assignee, sprint, release
|
|
91
90
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -100,13 +99,13 @@ ${i}
|
|
|
100
99
|
parent = excluded.parent,
|
|
101
100
|
assignee = excluded.assignee,
|
|
102
101
|
sprint = excluded.sprint,
|
|
103
|
-
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 Xd(e){let t=Ks(e.pmRoot),n=Kd();if(!n){await qt.rm(t,{force:!0});return}await qt.mkdir(Hd.dirname(t),{recursive:!0});let r=`${t}.${OE()}.tmp`,o;try{o=new n(r),LE(o),o.exec("BEGIN IMMEDIATE"),To(o,"version",Wd),To(o,"context_fingerprint",e.contextFingerprint),To(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Yd(o,i);o.exec("COMMIT"),o.close(),o=void 0,await qt.rm(t,{force:!0}),await qt.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([qt.rm(r,{force:!0})]),i}}function ME(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Jd(e){let t=Ks(e.pmRoot),n;try{await qt.access(t);let r=Kd();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=ME(n);if(o.version!==Wd||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&&Yd(n,e.row),To(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function So(e){await qt.rm(Ks(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 He=8,ru=500,$E="metadata-derived-index",jE="metadata-cache.json",UE="metadata-cache-bodies.json",zE="metadata-cache-collections.json",qE="metadata-cache-delta.json",BE="metadata-cache-manifest.json",Zd=4,GE=["comments","notes","learnings","files","tests","test_runs","docs"];function ou(){return Ze(G())}function xo(e){let t={...e},n={};for(let r of GE)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function iu(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function su(e,t,n,r){let o=FE("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 Co(e){return B.join(e,"runtime",jE)}function Io(e){return B.join(e,"runtime",UE)}function Oo(e){return B.join(e,"runtime",zE)}function Js(e){return B.join(e,"runtime",qE)}function Zs(e){return B.join(e,"runtime",BE)}function Ro(e,t){let n=B.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var VE=24,Ce=new Map,No=new WeakMap;function Qs(e){return No.get(e)??e.source_cursor}function HE(e,t){let n=Qs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){No.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 WE(e,t){if(!e)return;let n=Qs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){No.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 KE(e,t){if(!e)return;let n=Qs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){No.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 YE(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(HE(e,r),WE(t,r),KE(n,r))}function Ys(e,t){Ce.size>=VE&&!Ce.has(e)&&Kt(Ce),Ce.set(e,t)}async function yt(e,t){let n;try{n=await ce.stat(e)}catch{return Ce.delete(e),null}let r=Ce.get(e);if(r&&Hn(r.signature,n.mtimeMs,n.ctimeMs,n.size))return Ce.delete(e),Ce.set(e,r),r.envelope;let o;try{o=t(await ce.readFile(e,"utf8"))}catch{o=null}return Ys(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function XE(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==He||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=Co(e),i=await yt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await yt(Ro(o,t),r);return s===null&&Yn(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function JE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==He||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Io(e),o=await yt(r,n);return t&&o?.context_fingerprint!==t?await yt(Ro(r,t),n):o}async function ZE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==He||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Oo(e),o=await yt(r,n);return t&&o?.context_fingerprint!==t?await yt(Ro(r,t),n):o}async function au(e){let t=Js(e),n=await yt(t,r=>{let o=JSON.parse(r);return o.version!==He||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 cu(e){let t=Zs(e),n=await yt(t,r=>{let o=JSON.parse(r);return o.version!==He||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 Wn(e)}catch{}return null}async function Kn(e,t){await ce.mkdir(B.dirname(e),{recursive:!0}),await F(e,JSON.stringify(t));try{let r=await ce.stat(e);Ys(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{Ce.delete(e)}let n=B.dirname(B.dirname(e));if(e===Co(n)||e===Io(n)||e===Oo(n)){let r=Ro(e,t.context_fingerprint);await F(r,JSON.stringify(t));try{let c=await ce.stat(r);Ys(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{Ce.delete(r)}let o=B.dirname(e),i=B.extname(e),s=B.basename(e,i),a=(await ce.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==B.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>B.join(o,c.name));if(a.length>Zd){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-Zd)))await ce.rm(l.path,{force:!0}),Ce.delete(l.path)}}}function QE(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function lu(e,t,n){return e===void 0||QE(e,t,n)}function Yn(e,t){e&&!e.includes(t)&&e.push(t)}function Hn(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function ek(e,t,n){let r=B.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&&!te(o)&&Yn(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function tk(e,t){try{let n=await ce.stat(B.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 Xs(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await tk(e,n))))}function Ao(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&&Hn(o,r.mtime_ms,r.ctime_ms,r.size)})}function nk(e){return tn.some(t=>e.toLowerCase().endsWith(t))}function rk(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function ok(e,t,n){if(n)for(let r of await Le({path:e,scope:"project"}))Yn(t,r)}function Qd(e,t,n,r){if(e)return t&&n?n.collections:r}async function ik(e,t,n){let r=await ce.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=$r(e);await ok(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Hn(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Hn(d,o,i,s),f=n.previousCollections[t],m=!n.forceSourceRead&&f!==void 0&&Hn(f,o,i,s);if(!(!l||n.includeBody&&!u||n.includeCollections&&!m))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Qd(n.includeCollections,m,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let g=await ce.readFile(e,"utf8"),b=qe(g,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:k=>Yn(n.warnings,k)}),E=xo(b.metadata);return rk(n.state.misses,n.includeBody,n.includeCollections,l,u,m),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:E.light,heavyMetadata:Qd(n.includeCollections,m,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function sk(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?iu(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 ak(e,t,n,r){try{let o=await ik(t,n,r);sk(t,n,r,o)}catch{Yn(r.warnings,`item_list_item_read_failed:${e}/${B.basename(t)}`)}}function ck(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function lk(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function dk(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function uk(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function fk(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!nk(s))continue;let a=B.join(o,s),c=B.relative(t.pmRoot,a);n.push(ak(r,a,c,t))}return n}async function pk(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Ao(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Kn(Co(e.pmRoot),{version:He,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Kn(Zs(e.pmRoot),{version:He,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:B.relative(e.pmRoot,r.item_path),metadata:xo(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Xd({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await So(e.pmRoot)}catch{}}async function mk(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 Kn(Io(e.pmRoot),{version:He,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function _k(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 Kn(Oo(e.pmRoot),{version:He,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function ea(e,t,n={}){let r=await cu(e);return n.required!==!0&&(r===null||r.entry_count<ru)?async()=>{}:$e(e,$E,30,t,!1,!1,3e3)}function eu(e,t){let n=B.relative(e,t);return n===""||n===".."||n.startsWith(`..${B.sep}`)||B.isAbsolute(n)?null:n}async function Wn(e){await Promise.all([Co(e),Io(e),Oo(e),Js(e),Zs(e)].map(async t=>{await ce.rm(t,{force:!0}),Ce.delete(t)})),await So(e)}async function gk(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await ce.stat(e.mutation.itemPath),n=xo(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 hk(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function ta(e){let t=eu(e.pmRoot,e.itemPath),n=e.previousItemPath?eu(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Wn(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=su(e.preferredFormat,e.typeToFolder,e.schema,ou()),o=await cu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await au(e.pmRoot);if(s.invalid)return await Wn(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=hk(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 gk({mutation:e});let l=nu();return await Kn(Js(e.pmRoot),{version:He,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await Xs(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Jd({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:xo(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await So(e.pmRoot),[]}catch{return await Wn(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function yk(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function tu(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function bk(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function wk(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=$r(n);if(!o)continue;let i=e.includeCollections?iu(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:B.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function vk(e){return e.forceSourceScan||Br()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Ao(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||tu(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||tu(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&bk(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Do(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=ou(),l=su(t,n,o,c),d=await au(e);d.invalid&&await Wn(e);let u=await XE(e,l,i.cacheDiagnostics),f=s?await JE(e,l):null,m=a?await ZE(e,l):null;YE(u,f,m,d.envelope);let _=ck(u,l),g=lk(f,l),b=dk(m,l),E=[...new Set(Object.values(n))],k=await Xs(e,E),C=Object.keys(_),O=Math.max(1,Math.floor(i.derivedIndexMinimumItems??ru));if(vk({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:m,directorySignatures:k,entryKeys:C,minimumIndexedItems:O,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:b}))return wk({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:g,previousCollections:b});let A=await Promise.all(E.map(Q=>ek(e,Q,r))),L=Br(),N=uk(),re={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:L,previousEntries:_,previousBodies:g,previousCollections:b,state:N};await Promise.all(fk(A,re));let W=await Xs(e,E),le=Ao(k,W)?W:{},R=N.misses.metadata||Object.keys(_).length!==Object.keys(N.newEntries).length||!Ao(u?.directory_signatures,le)||u===null?nu():u.source_cursor;return await pk({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingCache:u,previousEntries:_,directorySignatures:le,state:N,minimumIndexedItems:O}),s&&await mk({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingBodyCache:f,previousBodies:g,state:N}),a&&await _k({pmRoot:e,contextFingerprint:l,sourceCursor:R,existingCollectionsCache:m,previousCollections:b,state:N}),yk(N)}async function du(e,t,n,r,o){return(await Do(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]="f49b5141-f348-5954-a87e-8fd957593113")}catch{}})();async function kk(e){try{return await Xn.access(e),!0}catch{return!1}}function Tk(e,t){e&&(e.includes(t)||e.push(t))}function Sk(e){return e??Ze(G())}function Ak(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=Te){let i=ht(t,n),s=un(t),a=i===s?[i]:[i,s],c=Object.entries(o),l=Ak(r);for(let d of a)for(let[u]of c)for(let f of l){let m=nn(e,u,d,f,o);if(await kk(m))return{id:d,type:u,itemPath:m,item_format:f}}return null}async function Ie(e,t={}){let n=await Xn.readFile(e.itemPath,"utf8");await Le({path:e.itemPath,scope:"project"});let r=qe(n,{format:e.item_format,schema:t.schema,extensionFieldNames:Sk(t.extensionFieldNames),onWarning:o=>Tk(t.warnings,o)});return{raw:n,document:r}}async function Jn(e,t,n=Te,r,o){return await Bn(e),(await du(e,t,n,r,o)).map(s=>s.metadata)}async function Po(e,t,n=Te,r,o,i={}){return await Bn(e),(await Do(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function uu(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 Ie(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>Jn(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function xk(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await Xn.readdir(Ek.join(e,o));for(let s of i)for(let a of tn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function Ck(e,t,n,r){let o=ht(t,n),i=await xk(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:It(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function fu(e,t,n,r){let o=await Ck(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 y(`Item ${t} not found`,h.NOT_FOUND,{nextSteps:i})}function Ik(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 Ok(e){let t=e.typeToFolder??ae(e.settings,G()).type_to_folder,n=await Ue(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await fu(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 Ie(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=es(e.author),d=Ut(e.settings);if(a&&c!==l&&!e.force&&!Ik(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new y(`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 Rk(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 Nk(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await F(e.originalItemPath,e.originalRaw),await Xn.rm(e.effectiveTargetItemPath,{force:!0});return}await F(e.originalItemPath,e.originalRaw)}}async function Dk(e){let t=await Ok({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=he(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=he(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=z();let f=he(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Ui({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:uu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let m=await Ws({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",g=xt(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=nn(e.pmRoot,f.metadata.type,r.id,_,n),E=Be(e.pmRoot,r.id),k=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:g}),{effectiveTargetItemPath:C,effectiveSerializedAfter:O,skipItemWrite:A}=Rk(k,b,g),L=await ea(e.pmRoot,e.author),N=[];try{A||await F(C,O),!A&&C!==r.itemPath&&await Xn.rm(r.itemPath);let W=Pn({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await oo(E,W)}catch(le){throw await Nk({skipItemWrite:A,effectiveTargetItemPath:C,originalItemPath:r.itemPath,originalRaw:o}),le}A||(N=await ta({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:C,previousItemPath:r.itemPath,document:f}))}finally{await L()}let re=[...await be({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 be({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 ji({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:qr(c.metadata,d.changedFields),current:qr(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...m.warnings,...k.warnings,...N,...re]}}finally{await a()}}async function Lo(e){return Dk(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 Lk(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Ut(e.settings);if(n.ownership_enforcement==="strict")throw new y(`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 Mk(e){let t=await X(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.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 Ie(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function pu(e){let t=e.writeHistoryRaw??F;try{await t(e.historyPath,e.nextHistoryRaw),await Je(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Pk.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Je(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function na(e){let t=[...Lk({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 Mk({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 fn from"node:fs/promises";import{createHash as Fk}from"node:crypto";import _u 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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var gu=4,$k="history-drift-cache.json";function hu(e){return _u.join(e,"runtime",$k)}async function jk(e){try{let t=await fn.readFile(hu(e),"utf8"),n=JSON.parse(t);return n.version!==gu||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function Uk(e,t,n,r,o){let i=uo(e),s;try{s=await fn.stat(i)}catch(l){return te(l)||o.unreadableStreams.push(pe),!1}let a=o.missingStreams.length,c=await bu({itemId:pe,historyPath:i,stat:s,cached:t[pe],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.chainOk||o.chainMismatches.push(pe),n[pe]={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,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function yu(e){return Fk("sha256").update(e).digest("hex")}async function zk(e){let t=await fn.readFile(e,"utf8");return yu(t)}async function qk(e){let t=await fn.readFile(e,"utf8"),n=yu(t);if(t.trim().length===0)return null;let r=[],o=null;for(let s of t.split(/\r?\n/)){let a=s.trim();if(a.length===0)continue;let c=JSON.parse(a);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),o=c.after_hash}if(!o)return null;let i=Dt(r);return{latestAfterHash:o,chainOk:i.ok,contentHash:n,itemHashVersion:i.item_hash_version??Fe}}function Bk(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function mu(e,t,n){try{let r=await qk(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function bu(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Bk(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await mu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await zk(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??Fe},cacheDirty:!1}:{verification:await mu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Gk(e,t,n,r){let o=Be(e,t.id),i;try{i=await fn.stat(o)}catch(d){return(te(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await bu({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.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,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return Dn({metadata:c,body:a},s.verification.itemHashVersion)!==s.verification.latestAfterHash&&r.hashMismatches.push(t.id),s.cacheDirty}async function Vk(e,t){if(!(t.unreadableStreams.includes(pe)||t.chainMismatches.includes(pe)))try{let n=await Rs(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(pe)}}async function Mo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await jk(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await Gk(e,f,l,r)&&(a=!0);let d=await Uk(e,i,s,c,r);if(a||=d,await Vk(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=hu(e);try{await fn.mkdir(_u.dirname(f),{recursive:!0}),await F(f,JSON.stringify({version:gu,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[pe]:[]])].sort((f,m)=>f.localeCompare(m));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 wu(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=ht(t,n.id_prefix),s=un(t),a=i===s?[i]:[i,s];for(let c of a){let l=Be(e,c);if(await q(l))return{id:c,historyPath:l,located:null}}throw new y(`Item ${t} not found`,h.NOT_FOUND)}import vu from"node:fs/promises";import Eu 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 Hk=[{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 Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ku(e){return Hk.find(t=>t.matches(e))?.kind}function Tu(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=Zn(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=Zn(u)?ku(u.value):void 0;if(f===void 0){a[d]=u;continue}c=!0,r+=1;let m=i.agent_harness??"unknown",_=`${m}\0${d}\0${f}`,g=t.get(_)??{harness:m,dimension:d,kind:f,count:0};g.count+=1,t.set(_,g)}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 Su(e){let t=[];for(let n of await Wk(e))try{let r=await vu.readFile(Eu.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
104
|
-
`)){if(o.trim().length===0)continue;let i=Kk(o);if(i===null||!Zn(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>Zn(a)&&ku(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Wk(e){try{return(await vu.readdir(Eu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function Kk(e){try{let t=JSON.parse(e);return Zn(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]="d201aa9f-1ed3-5655-8c06-e5729557b86a")}catch{}})();function Au(e,t){return t==="body"?e.body:e.metadata[t]}function ra(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)&&ra(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)&&ra(o,n[r]))}function xu(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 Fn(i.patch))s.add(Vn(c.path)),c.from&&s.add(Vn(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 Yk(e,t,n){let r=Cu.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(Vn(_.path));let i=new Set([...o].filter(_=>ra(Au(t,_),Au(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=xu(e,s),c=xu(e,i),l=[...o].sort((_,g)=>_.localeCompare(g)),d=[...s].sort((_,g)=>_.localeCompare(g)),u=[...i].sort((_,g)=>_.localeCompare(g)),f=[...new Set(a.map(_=>_.author))].sort((_,g)=>_.localeCompare(g)),m=[...new Set(c.map(_=>_.author))].sort((_,g)=>_.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:m,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 Xk(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Ie(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=us(i.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:Ae(s,r)===a,currentItemRawBeforeLock:i.raw,loadedItem:i}}function Jk(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 Zk(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:z(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Cu.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ae(e.finalReplay,e.itemHashVersion),after_hash:Ae(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function Qk(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 eT(e){return na({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})=>pu({historyPath:e.historyPath,nextHistoryRaw:pt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>be({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function oa(e,t,n){let r=oe(process.cwd(),n.path);await xe(r);let o=await Z(r),i=ae(o,G()),s=await wu(r,e,o,i.type_to_folder);if(!await q(s.historyPath))throw new y(`No history stream exists for ${s.id}.`,h.NOT_FOUND);let a=await X(s.historyPath),c=await dt(s.historyPath,s.id);if(c.length===0)throw new y(`No history entries exist for ${s.id}; nothing to repair.`,h.USAGE);let l=Pt(c),d=Dt(c),u=t.normalizeProvenance?Tu(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=fs(u.entries),m=new Set(u.entries.map(K=>K.item_hash_version).filter(K=>K!==void 0)),_=io(u.entries,f),g=await Xk(s,o,c,f),b=_.finalDocument,E=g.currentItemReplay!==null&&Ae(b,f)!==Ae(g.currentItemReplay,f),k=E&&g.currentItemReplay?Yk(_.entries,b,g.currentItemReplay):void 0,C=[_.entriesRehashed>0,_.entriesPatchRepaired>0,E,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),O=Me(t.author,o.author_default),A=!!t.dryRun,L=Jk({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:E}),{rewrittenEntries:N,auditEntryAdded:re}=Zk({reanchorEntries:_.entries,changed:C,reconcileNeeded:E,currentItemReplay:g.currentItemReplay,finalReplay:b,author:O,message:L,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...t.auditContext,provenance_normalization:u.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),W=Pt(N);if(!W.ok)throw new y(`history-repair produced an invalid rewritten chain (${W.errors.join(", ")}).`,h.GENERIC_FAILURE);let le=Qk(C,_.skippedOps,k);return C&&!A&&le.push(...await eT({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:O,force:t.force,loadedItem:g.loadedItem,historyPath:s.historyPath,rewrittenEntries:N})),{id:s.id,dry_run:A,changed:C,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:E,audit_entry_added:re,verify_ok:W.ok,verify_errors:W.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:m.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},...k?{reconciliation:k}:{},warnings:[...new Set(le)].sort((K,R)=>K.localeCompare(R)),generated_at:z()}}async function Iu(e,t){let n=oe(process.cwd(),t.path);await xe(n);let r=await Z(n),o=ae(r,G()),i=[],s=await Po(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await Mo(n,s),c=e.normalizeProvenance?await Su(n):[],l=[...new Set([...a.driftedItems,...c])].sort((m,_)=>m.localeCompare(_)),d=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let m of l)try{let _=await oa(m,{...e,auditContext:e.auditContextById?.[m],auditContextById:void 0},t),g=_.changed?"repaired":"skipped_clean";f[g]+=1,u.push(..._.warnings.map(b=>`${m}:${b}`)),d.push({id:m,outcome:g,entries_rehashed:_.history.entries_rehashed,entries_patch_repaired:_.history.entries_patch_repaired,reconciled_with_item:_.history.reconciled_with_item,..._.reconciliation?{reconciliation:_.reconciliation}:{},warnings:_.warnings})}catch(_){f.failed+=1,d.push({id:m,outcome:"failed",error:_ instanceof Error?_.message:String(_)})}return e.dryRun||await as(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((m,_)=>m.localeCompare(_)),generated_at:z()}}import tc from"node:fs/promises";import{realpathSync as Wx}from"node:fs";import{execFile as Kx}from"node:child_process";import _e from"node:path";import{promisify as Yx}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]="bc9e5edf-c275-5172-8900-fafee9b4a2db")}catch{}})();var tT=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:"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_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_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 nT(e){if(typeof e!="string")return;let t=e.trim();for(let n of tT)if(t===n.code||t.startsWith(`${n.code}:`))return n}function rT(e){let t={};for(let n of e){let r=nT(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Ou(e){return Object.values(rT(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 oT=["metadata","resolution"],ia=["metadata","resolution","estimates","lifecycle"],iT="completed";function sa(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ru(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Nu(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Ru(n.close_reason)??iT;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${sa(r)}`,gate:"resolution"})}return t}function Du(e){let t=[];for(let n of e){let r=Ru(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 ${sa(r)}`,gate:"metadata"})}return t}function Pu(e,t){return e.map(n=>{let r=kd(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 Lu(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 Mu(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 ${sa(n.path)}`})}return t}function Fu(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 y(`--fix-scope values must not be empty. Supported values: ${ia.join(", ")}.`,h.USAGE);return new Set(oT)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(ia.includes(o)){n.add(o);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${ia.join(", ")}.`,h.USAGE)}return n}function $u(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 Qn(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var sT=/^([A-Z][A-Z0-9]*-\d+)\b/;function aT(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=sT.exec(t);return n?n[1]:null}function ju(e){return typeof e=="string"&&e.trim().length>0}function Uu(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||ju(r.duplicate_of))continue;let o=aT(r.title);if(o===null)continue;let i=t.get(o);i||(i=[],t.set(o,i)),i.some(s=>s.id===r.id)||i.push({id:r.id,title:r.title,parent:ju(r.parent)?r.parent.trim():null})}let n=[];for(let[r,o]of t){if(o.length<2)continue;let i=new Set(o.map(c=>c.id.toLowerCase())),s=o.filter(c=>c.parent===null||!i.has(c.parent.toLowerCase()));if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((r,o)=>r.code.localeCompare(o.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 zu(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 qu=3;function Bu(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Gu(e,t,n=qu){let r=Number.isFinite(n)&&n>=1?Math.floor(n):qu,o=new Map;for(let i of t){let s=Bu(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(Bu(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 Vu(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 cT=/^[a-z][a-z0-9+.-]+:\/\//i;function er(e){return cT.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 lT(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Hu(e){return`${e.item_id} ${e.link_kind}`}function Wu(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=lT(o.classification,r.classification),o.owners.set(Hu(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Hu(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 dT(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ku(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="${dT(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]="1b2f1ac3-82b3-58a2-9f40-2dd95ab1b2bc")}catch{}})();var uT="global",fT="external";function Yu(e){let t=e?.trim().toLowerCase();return t===uT||t===fT}(function(){try{var e=typeof window<"u"?window:typeof 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 Bt(){let e=rn();for(let t of G()?.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 $o(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Fo(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function pT(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 mT(e,t){let n=[...e].sort(),r=pT(n,t),o=new Set,i=_T(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=gT(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 _T(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 gT(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 hT(e){let t=new Map;for(let n of e){let r=$o(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function yT(e,t,n){let r=$o(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 bT(e,t,n,r){let o=$o(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 wT(e,t){let n=new Map;for(let[r,o]of e){let i=yT(r,o,e);i&&n.set(Fo(i),i);for(let s of o.dependencies??[]){let a=bT(r,s,e,t);a&&n.set(Fo(a),a)}}return[...n.values()].sort((r,o)=>Fo(r).localeCompare(Fo(o)))}function vT(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 ET(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=$o(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 aa(e,t=r=>r==="closed"||r==="canceled",n=Bt()){let r=hT(e),o=wT(r,n),i=kT(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=mT([...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:vT(o,i.parents_by_child,s),divergences:ET(r,o,s)}}function kT(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]="9a6974b3-63d7-5dc7-8329-0f15f0dc83ec")}catch{}})();function TT(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function Xu(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)=>{let f=TT(l);if(!f||r.has(f.toLowerCase()))return;let m={holder_id:c.id.trim(),target_id:f,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:f.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"),i(c,c.blocked_by,"blocked_by","blocked_by");for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;Yu(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency")}}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 pn from"node:fs/promises";import mn 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 ST(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await pn.readdir(mn.join(e,o))}catch{return}for(let s of i)for(let a of tn)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 AT(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Pe(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 ca(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 xT(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await pn.readdir(mn.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 pn.readFile(mn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:ca("history stream",s)});continue}AT({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function Ju(e){let t=Pe(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 CT(e){let t=[],n=0,r=null;try{r=await X(ye(e))}catch(i){n+=1,t.push({path:"settings.json",detail:ca("configuration file",i)})}if(r!==null){n+=1;let i=Ju(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await pn.readdir(mn.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 pn.readFile(mn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:ca("configuration file",c)});continue}let a=Ju(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function Zu(e,t,n,r={}){let o=await ST(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((m,_)=>m.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=mn.join(e,u.relativePath);return qe(await pn.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 xT(e,i),d=await CT(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 IT}from"node:child_process";import{realpath as OT}from"node:fs/promises";import Qu from"node:path";import{promisify as RT}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 NT=RT(IT),DT=32*1024*1024,PT=1e4,LT=["search/eval-queries.json"];function la(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function MT(e){return`'${e.replaceAll("'","'\\''")}'`}async function FT(e,t=OT){return t(e).catch(()=>Qu.resolve(e))}async function ef(e){let t=await dn(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 FT(e),r=la(Qu.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=Dd.map(i=>`${r}/${la(i)}`);try{let{stdout:i}=await NT("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:DT,windowsHide:!0,timeout:PT}),s=new Set(LT.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(la(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=>MT(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Ga from"node:fs/promises";import Va from"node:path";import{Option as KH}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]="2252cfb9-37ea-57f1-b7ea-2b0c0f87ecb2")}catch{}})();var _n="-",tf=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 da(e){return e.replace(/\r\n/g,`
|
|
105
|
-
`)}function
|
|
102
|
+
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 uu(e){let t=ra(e.pmRoot),n=lu();if(!n){await Bt.rm(t,{force:!0});return}await Bt.mkdir(au.dirname(t),{recursive:!0});let r=`${t}.${_k()}.tmp`,o;try{o=new n(r),wk(o),o.exec("BEGIN IMMEDIATE"),Oo(o,"version",cu),Oo(o,"context_fingerprint",e.contextFingerprint),Oo(o,"source_cursor",e.sourceCursor);for(let i of e.rows)du(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Bt.rm(t,{force:!0}),await Bt.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Bt.rm(r,{force:!0})]),i}}function vk(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function fu(e){let t=ra(e.pmRoot),n;try{await Bt.access(t);let r=lu();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=vk(n);if(o.version!==cu||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&&du(n,e.row),Oo(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function Ro(e){await Bt.rm(ra(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 We=8,yu=500,kk="metadata-derived-index",Tk="metadata-cache.json",Sk="metadata-cache-bodies.json",Ak="metadata-cache-collections.json",xk="metadata-cache-delta.json",Ck="metadata-cache-manifest.json",pu=4,Ik=["comments","notes","learnings","files","tests","test_runs","docs"];function bu(){return Qe(V())}function Do(e){let t={...e},n={};for(let r of Ik)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function wu(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function vu(e,t,n,r){let o=Ek("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 Po(e){return G.join(e,"runtime",Tk)}function Lo(e){return G.join(e,"runtime",Sk)}function Mo(e){return G.join(e,"runtime",Ak)}function sa(e){return G.join(e,"runtime",xk)}function aa(e){return G.join(e,"runtime",Ck)}function Fo(e,t){let n=G.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var Ok=24,Oe=new Map,$o=new WeakMap;function ca(e){return $o.get(e)??e.source_cursor}function Rk(e,t){let n=ca(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){$o.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 Nk(e,t){if(!e)return;let n=ca(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){$o.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 Dk(e,t){if(!e)return;let n=ca(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){$o.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 Pk(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(Rk(e,r),Nk(t,r),Dk(n,r))}function oa(e,t){Oe.size>=Ok&&!Oe.has(e)&&Yt(Oe),Oe.set(e,t)}async function wt(e,t){let n;try{n=await de.stat(e)}catch{return Oe.delete(e),null}let r=Oe.get(e);if(r&&Zn(r.signature,n.mtimeMs,n.ctimeMs,n.size))return Oe.delete(e),Oe.set(e,r),r.envelope;let o;try{o=t(await de.readFile(e,"utf8"))}catch{o=null}return oa(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function Lk(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==We||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=Po(e),i=await wt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await wt(Fo(o,t),r);return s===null&&tr(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function Mk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==We||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Lo(e),o=await wt(r,n);return t&&o?.context_fingerprint!==t?await wt(Fo(r,t),n):o}async function Fk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==We||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Mo(e),o=await wt(r,n);return t&&o?.context_fingerprint!==t?await wt(Fo(r,t),n):o}async function Eu(e){let t=sa(e),n=await wt(t,r=>{let o=JSON.parse(r);return o.version!==We||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 de.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function ku(e){let t=aa(e),n=await wt(t,r=>{let o=JSON.parse(r);return o.version!==We||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 de.stat(t),await Qn(e)}catch{}return null}async function er(e,t){await de.mkdir(G.dirname(e),{recursive:!0}),await $(e,JSON.stringify(t));try{let r=await de.stat(e);oa(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{Oe.delete(e)}let n=G.dirname(G.dirname(e));if(e===Po(n)||e===Lo(n)||e===Mo(n)){let r=Fo(e,t.context_fingerprint);await $(r,JSON.stringify(t));try{let c=await de.stat(r);oa(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{Oe.delete(r)}let o=G.dirname(e),i=G.extname(e),s=G.basename(e,i),a=(await de.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>pu){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await de.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-pu)))await de.rm(l.path,{force:!0}),Oe.delete(l.path)}}}function $k(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Tu(e,t,n){return e===void 0||$k(e,t,n)}function tr(e,t){e&&!e.includes(t)&&e.push(t)}function Zn(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function jk(e,t,n){let r=G.join(e,t);try{let o=await de.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!te(o)&&tr(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function Uk(e,t){try{let n=await de.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 ia(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await Uk(e,n))))}function No(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&&Zn(o,r.mtime_ms,r.ctime_ms,r.size)})}function zk(e){return nn.some(t=>e.toLowerCase().endsWith(t))}function qk(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function Bk(e,t,n){if(n)for(let r of await Me({path:e,scope:"project"}))tr(t,r)}function mu(e,t,n,r){if(e)return t&&n?n.collections:r}async function Gk(e,t,n){let r=await de.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Vr(e);await Bk(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Zn(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Zn(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&Zn(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:mu(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let g=await de.readFile(e,"utf8"),b=xe(g,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:k=>tr(n.warnings,k)}),T=Do(b.metadata);return qk(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:T.light,heavyMetadata:mu(n.includeCollections,p,f,T.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function Vk(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?wu(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};Tu(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function Hk(e,t,n,r){try{let o=await Gk(t,n,r);Vk(t,n,r,o)}catch{tr(r.warnings,`item_list_item_read_failed:${e}/${G.basename(t)}`)}}function Wk(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function Kk(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function Yk(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function Xk(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function Jk(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!zk(s))continue;let a=G.join(o,s),c=G.relative(t.pmRoot,a);n.push(Hk(r,a,c,t))}return n}async function Zk(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!No(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await er(Po(e.pmRoot),{version:We,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await er(aa(e.pmRoot),{version:We,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:Do(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await uu({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Ro(e.pmRoot)}catch{}}async function Qk(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 er(Lo(e.pmRoot),{version:We,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function eT(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 er(Mo(e.pmRoot),{version:We,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function la(e,t,n={}){let r=await ku(e);return n.required!==!0&&(r===null||r.entry_count<yu)?async()=>{}:je(e,kk,30,t,!1,!1,3e3)}function _u(e,t){let n=G.relative(e,t);return n===""||n===".."||n.startsWith(`..${G.sep}`)||G.isAbsolute(n)?null:n}async function Qn(e){await Promise.all([Po(e),Lo(e),Mo(e),sa(e),aa(e)].map(async t=>{await de.rm(t,{force:!0}),Oe.delete(t)})),await Ro(e)}async function tT(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await de.stat(e.mutation.itemPath),n=Do(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 nT(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function da(e){let t=_u(e.pmRoot,e.itemPath),n=e.previousItemPath?_u(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Qn(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=vu(e.preferredFormat,e.typeToFolder,e.schema,bu()),o=await ku(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await Eu(e.pmRoot);if(s.invalid)return await Qn(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=nT(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 tT({mutation:e});let l=hu();return await er(sa(e.pmRoot),{version:We,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await ia(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await fu({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:Do(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Ro(e.pmRoot),[]}catch{return await Qn(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function rT(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function gu(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function oT(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function iT(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Vr(n);if(!o)continue;let i=e.includeCollections?wu(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Tu(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 sT(e){return e.forceSourceScan||Xr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!No(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||gu(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||gu(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&oT(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function jo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=bu(),l=vu(t,n,o,c),d=await Eu(e);d.invalid&&await Qn(e);let u=await Lk(e,l,i.cacheDiagnostics),f=s?await Mk(e,l):null,p=a?await Fk(e,l):null;Pk(u,f,p,d.envelope);let _=Wk(u,l),g=Kk(f,l),b=Yk(p,l),T=[...new Set(Object.values(n))],k=await ia(e,T),I=Object.keys(_),x=Math.max(1,Math.floor(i.derivedIndexMinimumItems??yu));if(sT({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:k,entryKeys:I,minimumIndexedItems:x,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:b}))return iT({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:g,previousCollections:b});let v=await Promise.all(T.map(z=>jk(e,z,r))),N=Xr(),P=Xk(),ie={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:N,previousEntries:_,previousBodies:g,previousCollections:b,state:P};await Promise.all(Jk(v,ie));let Q=await ia(e,T),fe=No(k,Q)?Q:{},D=P.misses.metadata||Object.keys(_).length!==Object.keys(P.newEntries).length||!No(u?.directory_signatures,fe)||u===null?hu():u.source_cursor;return await Zk({pmRoot:e,contextFingerprint:l,sourceCursor:D,existingCache:u,previousEntries:_,directorySignatures:fe,state:P,minimumIndexedItems:x}),s&&await Qk({pmRoot:e,contextFingerprint:l,sourceCursor:D,existingBodyCache:f,previousBodies:g,state:P}),a&&await eT({pmRoot:e,contextFingerprint:l,sourceCursor:D,existingCollectionsCache:p,previousCollections:b,state:P}),rT(P)}async function Su(e,t,n,r,o){return(await jo(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]="f49b5141-f348-5954-a87e-8fd957593113")}catch{}})();async function cT(e){try{return await nr.access(e),!0}catch{return!1}}function lT(e,t){e&&(e.includes(t)||e.push(t))}function dT(e){return e??Qe(V())}function uT(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=Se){let i=bt(t,n),s=un(t),a=i===s?[i]:[i,s],c=Object.entries(o),l=uT(r);for(let d of a)for(let[u]of c)for(let f of l){let p=rn(e,u,d,f,o);if(await cT(p))return{id:d,type:u,itemPath:p,item_format:f}}return null}async function Re(e,t={}){let n=await nr.readFile(e.itemPath,"utf8");await Me({path:e.itemPath,scope:"project"});let r=xe(n,{format:e.item_format,schema:t.schema,extensionFieldNames:dT(t.extensionFieldNames),onWarning:o=>lT(t.warnings,o)});return{raw:n,document:r}}async function rr(e,t,n=Se,r,o){return await Yn(e),(await Su(e,t,n,r,o)).map(s=>s.metadata)}async function Uo(e,t,n=Se,r,o,i={}){return await Yn(e),(await jo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function Au(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 Re(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>rr(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function fT(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await nr.readdir(aT.join(e,o));for(let s of i)for(let a of nn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function pT(e,t,n,r){let o=bt(t,n),i=await fT(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Rt(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function xu(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 y(`Item ${t} not found`,h.NOT_FOUND,{nextSteps:i})}function mT(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 _T(e){let t=e.typeToFolder??le(e.settings,V()).type_to_folder,n=await ze(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await xu(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await je(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 Re(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=is(e.author),d=zt(e.settings);if(a&&c!==l&&!e.force&&!mT(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new y(`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 gT(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 hT(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await $(e.originalItemPath,e.originalRaw),await nr.rm(e.effectiveTargetItemPath,{force:!0});return}await $(e.originalItemPath,e.originalRaw)}}async function yT(e){let t=await _T({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=be(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=be(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=be(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Vi({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:Au({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await na({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",g=It(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=rn(e.pmRoot,f.metadata.type,r.id,_,n),T=Be(e.pmRoot,r.id),k=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:T,item_format:_,before:c,after:f,contents:g}),{effectiveTargetItemPath:I,effectiveSerializedAfter:x,skipItemWrite:v}=gT(k,b,g),N=await la(e.pmRoot,e.author),P=[];try{v||await $(I,x),!v&&I!==r.itemPath&&await nr.rm(r.itemPath);let Q=Fn({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await uo(T,Q)}catch(fe){throw await hT({skipItemWrite:v,effectiveTargetItemPath:I,originalItemPath:r.itemPath,originalRaw:o}),fe}v||(P=await da({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:I,previousItemPath:r.itemPath,document:f}))}finally{await N()}let ie=[...await ve({path:I,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await ve({path:T,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 Gi({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:Yr(c.metadata,d.changedFields),current:Yr(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...k.warnings,...P,...ie]}}finally{await a()}}async function zo(e){return yT(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 wT(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=zt(e.settings);if(n.ownership_enforcement==="strict")throw new y(`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 vT(e){let t=await X(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`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 Re(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Cu(e){let t=e.writeHistoryRaw??$;try{await t(e.historyPath,e.nextHistoryRaw),await Ze(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await bT.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Ze(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function ua(e){let t=[...wT({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await je(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 vT({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 fn from"node:fs/promises";import{createHash as ET}from"node:crypto";import Ou 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]="32538934-2cbb-50fe-b721-ad9197cef7d8")}catch{}})();var Ru=4,kT="history-drift-cache.json";function Nu(e){return Ou.join(e,"runtime",kT)}async function TT(e){try{let t=await fn.readFile(Nu(e),"utf8"),n=JSON.parse(t);return n.version!==Ru||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function ST(e,t,n,r,o){let i=ho(e),s;try{s=await fn.stat(i)}catch(l){return te(l)||o.unreadableStreams.push(_e),!1}let a=o.missingStreams.length,c=await Pu({itemId:_e,historyPath:i,stat:s,cached:t[_e],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.chainOk||o.chainMismatches.push(_e),n[_e]={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,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function Du(e){return ET("sha256").update(e).digest("hex")}async function AT(e){let t=await fn.readFile(e,"utf8");return Du(t)}async function xT(e){let t=await fn.readFile(e,"utf8"),n=Du(t);if(t.trim().length===0)return null;let r=[],o=null;for(let s of t.split(/\r?\n/)){let a=s.trim();if(a.length===0)continue;let c=JSON.parse(a);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(c),o=c.after_hash}if(!o)return null;let i=Lt(r);return{latestAfterHash:o,chainOk:i.ok,contentHash:n,itemHashVersion:i.item_hash_version??$e}}function CT(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Iu(e,t,n){try{let r=await xT(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Pu(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(CT(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Iu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await AT(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r,itemHashVersion:e.cached.item_hash_version??$e},cacheDirty:!1}:{verification:await Iu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function IT(e,t,n,r){let o=Be(e,t.id),i;try{i=await fn.stat(o)}catch(d){return(te(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Pu({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.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,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return Mn({metadata:c,body:a},s.verification.itemHashVersion)!==s.verification.latestAfterHash&&r.hashMismatches.push(t.id),s.cacheDirty}async function OT(e,t){if(!(t.unreadableStreams.includes(_e)||t.chainMismatches.includes(_e)))try{let n=await Us(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(_e)}}async function qo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await TT(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await IT(e,f,l,r)&&(a=!0);let d=await ST(e,i,s,c,r);if(a||=d,await OT(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=Nu(e);try{await fn.mkdir(Ou.dirname(f),{recursive:!0}),await $(f,JSON.stringify({version:Ru,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[_e]:[]])].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 Lu(e,t,n,r){let o=await ze(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Be(e,o.id),located:o};let i=bt(t,n.id_prefix),s=un(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 y(`Item ${t} not found`,h.NOT_FOUND)}import Mu from"node:fs/promises";import Fu 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 RT=[{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 or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $u(e){return RT.find(t=>t.matches(e))?.kind}function ju(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=or(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=or(u)?$u(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}`,g=t.get(_)??{harness:p,dimension:d,kind:f,count:0};g.count+=1,t.set(_,g)}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 Uu(e){let t=[];for(let n of await NT(e))try{let r=await Mu.readFile(Fu.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
103
|
+
`)){if(o.trim().length===0)continue;let i=DT(o);if(i===null||!or(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>or(a)&&$u(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function NT(e){try{return(await Mu.readdir(Fu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function DT(e){try{let t=JSON.parse(e);return or(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]="7a21ee76-ed53-57a0-9776-c787297ed7b6")}catch{}})();function zu(e,t){return t==="body"?e.body:e.metadata[t]}function fa(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)&&fa(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)&&fa(o,n[r]))}function qu(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 Un(i.patch))s.add(Jn(c.path)),c.from&&s.add(Jn(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 LT(e,t,n){let r=Gu.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(Jn(_.path));let i=new Set([...o].filter(_=>fa(zu(t,_),zu(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=qu(e,s),c=qu(e,i),l=[...o].sort((_,g)=>_.localeCompare(g)),d=[...s].sort((_,g)=>_.localeCompare(g)),u=[...i].sort((_,g)=>_.localeCompare(g)),f=[...new Set(a.map(_=>_.author))].sort((_,g)=>_.localeCompare(g)),p=[...new Set(c.map(_=>_.author))].sort((_,g)=>_.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 MT(e){try{return await Bu(e)}catch{return null}}async function FT(e){if(e.receipt.evidence_source!=="clone_local"||await MT(PT.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((a,c)=>a.localeCompare(c)),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let o=Object.keys(r).sort((a,c)=>a.localeCompare(c));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]===ce(O(c))})?{receipt:e.receipt,declaredFields:n}:null}async function $T(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 Bu(e.itemPath),r=[];for(let s of t){let a=await FT({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_clone_local_driver_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function jT(e){let t=e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId)??[],n=e.options.mergeReceiptProof?await $T({proof:{...e.options.mergeReceiptProof,receipts:t},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(n&&!n.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${n.reason}).`,h.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use clone-local driver 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 r=n?.trusted?t.filter(o=>n.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:n,effectiveAuditContext:r.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:r.map(Ve)}}:e.options.auditContext}}async function UT(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Re(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=hs(i.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:Ce(s,r)===a,currentItemRawBeforeLock:i.raw,loadedItem:i}}function zT(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 qT(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:q(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Gu.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ce(e.finalReplay,e.itemHashVersion),after_hash:Ce(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function BT(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 GT(e){return ua({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})=>Cu({historyPath:e.historyPath,nextHistoryRaw:mt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ve({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function pa(e,t,n){let r=ne(process.cwd(),n.path);await Ie(r);let o=await Z(r),i=le(o,V()),s=await Lu(r,e,o,i.type_to_folder);if(!await B(s.historyPath))throw new y(`No history stream exists for ${s.id}.`,h.NOT_FOUND);let a=await X(s.historyPath),c=await ut(s.historyPath,s.id);if(c.length===0)throw new y(`No history entries exist for ${s.id}; nothing to repair.`,h.USAGE);let l=Mt(c),d=Lt(c),u=t.normalizeProvenance?ju(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=ys(u.entries),p=new Set(u.entries.map(z=>z.item_hash_version).filter(z=>z!==void 0)),_=fo(u.entries,f),g=await UT(s,o,c,f),b=_.finalDocument,T=g.currentItemReplay!==null&&Ce(b,f)!==Ce(g.currentItemReplay,f),k=T&&g.currentItemReplay?LT(_.entries,b,g.currentItemReplay):void 0,{mergeReceiptProof:I,effectiveAuditContext:x}=await jT({options:t,subjectId:s.id,itemReplayContext:g,reconciliation:k}),v=[_.entriesRehashed>0,_.entriesPatchRepaired>0,T,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),N=Fe(t.author,o.author_default),P=!!t.dryRun,ie=zT({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:T}),{rewrittenEntries:Q,auditEntryAdded:fe}=qT({reanchorEntries:_.entries,changed:v,reconcileNeeded:T,currentItemReplay:g.currentItemReplay,finalReplay:b,author:N,message:ie,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...x,provenance_normalization:u.receipt}:x,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),Y=Mt(Q);if(!Y.ok)throw new y(`history-repair produced an invalid rewritten chain (${Y.errors.join(", ")}).`,h.GENERIC_FAILURE);let D=BT(v,_.skippedOps,k);return v&&!P&&D.push(...await GT({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:N,force:t.force,loadedItem:g.loadedItem,historyPath:s.historyPath,rewrittenEntries:Q})),{id:s.id,dry_run:P,changed:v,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:T,audit_entry_added:fe,verify_ok:Y.ok,verify_errors:Y.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},...k?{reconciliation:k}:{},...I?{merge_receipt_proof:I}:{},warnings:[...new Set(D)].sort((z,hr)=>z.localeCompare(hr)),generated_at:q()}}async function Vu(e,t){let n=ne(process.cwd(),t.path);await Ie(n);let r=await Z(n),o=le(r,V()),i=[],s=await Uo(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await qo(n,s),c=e.normalizeProvenance?await Uu(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 pa(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),g=_.changed?"repaired":"skipped_clean";f[g]+=1,u.push(..._.warnings.map(b=>`${p}:${b}`)),d.push({id:p,outcome:g,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 ps(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 dc from"node:fs/promises";import{realpathSync as FC}from"node:fs";import{execFile as $C}from"node:child_process";import he from"node:path";import{promisify as jC}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]="c088607b-1be3-54c8-a38b-79c188924102")}catch{}})();var VT=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 --dry-run",summary:"A lossless merge receipt is still pending; preview and run pm merge reconcile so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm health --check-only --full",summary:"One or more receipt files failed bounded-file, schema, or identity validation; use the full health count to inspect the clone-local and durable receipt directories, then repair or remove only confirmed invalid evidence."},{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_merge_receipt",command:"pm merge reconcile --dry-run",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; preview reconciliation 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_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 HT(e){if(typeof e!="string")return;let t=e.trim();for(let n of VT)if(t===n.code||t.startsWith(`${n.code}:`))return n}function WT(e){let t={};for(let n of e){let r=HT(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Hu(e){return Object.values(WT(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 KT=["metadata","resolution"],ma=["metadata","resolution","estimates","lifecycle"],YT="completed";function _a(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Wu(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ku(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Wu(n.close_reason)??YT;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${_a(r)}`,gate:"resolution"})}return t}function Yu(e){let t=[];for(let n of e){let r=Wu(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 ${_a(r)}`,gate:"metadata"})}return t}function Xu(e,t){return e.map(n=>{let r=$d(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 Ju(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 Zu(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 ${_a(n.path)}`})}return t}function Qu(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 y(`--fix-scope values must not be empty. Supported values: ${ma.join(", ")}.`,h.USAGE);return new Set(KT)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(ma.includes(o)){n.add(o);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${ma.join(", ")}.`,h.USAGE)}return n}function ef(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 ir(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var XT=/^([A-Z][A-Z0-9]*-\d+)\b/;function JT(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=XT.exec(t);return n?n[1]:null}function tf(e){return typeof e=="string"&&e.trim().length>0}function nf(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||tf(r.duplicate_of))continue;let o=JT(r.title);if(o===null)continue;let i=t.get(o);i||(i=[],t.set(o,i)),i.some(s=>s.id===r.id)||i.push({id:r.id,title:r.title,parent:tf(r.parent)?r.parent.trim():null})}let n=[];for(let[r,o]of t){if(o.length<2)continue;let i=new Set(o.map(c=>c.id.toLowerCase())),s=o.filter(c=>c.parent===null||!i.has(c.parent.toLowerCase()));if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((r,o)=>r.code.localeCompare(o.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 rf(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 of=3;function sf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function af(e,t,n=of){let r=Number.isFinite(n)&&n>=1?Math.floor(n):of,o=new Map;for(let i of t){let s=sf(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(sf(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 cf(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 ZT=/^[a-z][a-z0-9+.-]+:\/\//i;function sr(e){return ZT.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 QT(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function lf(e){return`${e.item_id} ${e.link_kind}`}function df(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=QT(o.classification,r.classification),o.owners.set(lf(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[lf(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 uf(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]="1b2f1ac3-82b3-58a2-9f40-2dd95ab1b2bc")}catch{}})();var tS="global",nS="external";function ff(e){let t=e?.trim().toLowerCase();return t===tS||t===nS}(function(){try{var e=typeof window<"u"?window:typeof 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 Gt(){let e=on();for(let t of V()?.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 Go(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Bo(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function rS(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 oS(e,t){let n=[...e].sort(),r=rS(n,t),o=new Set,i=iS(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=sS(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 iS(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 sS(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 aS(e){let t=new Map;for(let n of e){let r=Go(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function cS(e,t,n){let r=Go(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 lS(e,t,n,r){let o=Go(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 dS(e,t){let n=new Map;for(let[r,o]of e){let i=cS(r,o,e);i&&n.set(Bo(i),i);for(let s of o.dependencies??[]){let a=lS(r,s,e,t);a&&n.set(Bo(a),a)}}return[...n.values()].sort((r,o)=>Bo(r).localeCompare(Bo(o)))}function uS(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 fS(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=Go(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 ga(e,t=r=>r==="closed"||r==="canceled",n=Gt()){let r=aS(e),o=dS(r,n),i=pS(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=oS([...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:uS(o,i.parents_by_child,s),divergences:fS(r,o,s)}}function pS(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]="9a6974b3-63d7-5dc7-8329-0f15f0dc83ec")}catch{}})();function mS(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function pf(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)=>{let f=mS(l);if(!f||r.has(f.toLowerCase()))return;let p={holder_id:c.id.trim(),target_id:f,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:f.toLowerCase()==="no-active-blocker"};o.set(`${p.holder_id}::${p.target_id}::${p.kind}::${p.source}`,p)};for(let c of n){i(c,c.parent,"parent","parent"),i(c,c.blocked_by,"blocked_by","blocked_by");for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;ff(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency")}}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 pn from"node:fs/promises";import mn 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 _S(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await pn.readdir(mn.join(e,o))}catch{return}for(let s of i)for(let a of nn)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 gS(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 ha(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 hS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await pn.readdir(mn.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 pn.readFile(mn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:ha("history stream",s)});continue}gS({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function mf(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 yS(e){let t=[],n=0,r=null;try{r=await X(we(e))}catch(i){n+=1,t.push({path:"settings.json",detail:ha("configuration file",i)})}if(r!==null){n+=1;let i=mf(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await pn.readdir(mn.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 pn.readFile(mn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:ha("configuration file",c)});continue}let a=mf(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function _f(e,t,n,r={}){let o=await _S(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=mn.join(e,u.relativePath);return xe(await pn.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 hS(e,i),d=await yS(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 bS}from"node:child_process";import{realpath as wS}from"node:fs/promises";import gf from"node:path";import{promisify as vS}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 ES=vS(bS),kS=32*1024*1024,TS=1e4,SS=["search/eval-queries.json"];function ya(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function AS(e){return`'${e.replaceAll("'","'\\''")}'`}async function xS(e,t=wS){return t(e).catch(()=>gf.resolve(e))}async function hf(e){let t=await yt(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 xS(e),r=ya(gf.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=Kd.map(i=>`${r}/${ya(i)}`);try{let{stdout:i}=await ES("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:kS,windowsHide:!0,timeout:TS}),s=new Set(SS.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(ya(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=>AS(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Qa from"node:fs/promises";import ec from"node:path";import{Option as Z5}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]="2252cfb9-37ea-57f1-b7ea-2b0c0f87ecb2")}catch{}})();var _n="-",yf=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 ba(e){return e.replace(/\r\n/g,`
|
|
104
|
+
`)}function bf(e){let t=ba(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
|
|
106
105
|
`);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
|
|
107
|
-
`)}function
|
|
108
|
-
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=
|
|
109
|
-
`).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]=
|
|
110
|
-
${i}`;continue}return null}return n}function gn(e,t){let n=nf(e).trim();if(!n)throw new y(`${t} cannot be empty`,h.USAGE);let r=qT(n);if(r)return r;let o={},i,s=$T(n);for(let a of s){let c=jT(a);if(c>0){let l=a.slice(0,c).trim(),d=rf(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&tf.has(i.toLowerCase())){o[i]=`${o[i]},${a.trim()}`;continue}throw new y(zT(e,t),h.USAGE)}return o}var BT=/^[A-Za-z]:[\\/]/,GT=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function ua(e){let t=e.trim();return BT.test(t)?!1:GT.test(t)}function hn(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 y(`${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 y(`${t} provides key "${i}" more than once after case normalization.`,h.USAGE);e[s]=e[i],delete e[i]}}}async function VT(e){if(process.stdin.isTTY===!0)throw new y(`${e} value "${_n}" 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(da(r))}),process.stdin.on("error",o=>{n(o)})})}function tr(){let e,t,n=async i=>{if(t&&t!==i)throw new y(`Only one option may use "${_n}" stdin token per command invocation. Already used by ${t}.`,h.USAGE);return t=i,e||(e=VT(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==_n?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()===_n?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new y(`${s} accepts "${_n}" 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]="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 HT={critical:0,high:1,medium:2,low:3,minimal:4},WT=Object.keys(HT),dU=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${WT.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 xU=new Map(ai.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 pS}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 mS=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Dz=new RegExp(`\\b(${mS.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var Pz=pS(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 Fz=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]="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 gS=[{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"}],Wz=new Map(gS.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 tq=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 fa(e,t){if(e==null)return[];let n=t?.separators??/,/,o=e.split(n).map(a=>a.trim()).filter(a=>a.length>0),s=t?.unique!==!1?Array.from(new Set(o)):o;return t?.sort===!0?[...s].sort():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]="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 mq 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 bS from"node:crypto";import pa 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 Iq=pa.join("runtime","telemetry","events.jsonl"),Oq=pa.join("runtime","telemetry","state.json"),Rq=pa.join("runtime","telemetry","otel-spans.jsonl");var Nq=3600*1e3;var Dq=globalThis.fetch,wS=["user","automation","test","dogfood"],Pq=Promise.resolve(),Lq=Promise.resolve();var Mq=new Set(wS);var Fq=bS.randomUUID();var uf="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",$q=new RegExp(`\\b(${uf})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),jq=new RegExp(`(--${uf})(=|\\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]="be6f7869-f197-5d38-b8d9-faf8f390cd56")}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 ma=[{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}],ff=ma.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),pf=ma.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),_a=[{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}],ga=_a.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),mf=_a.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 ha=[{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"}],_f=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],RS=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},..._f],gf=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],NS=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],DS=[...ha,...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"}],PS=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],yf=[{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"}],ya=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...se(ha),...se(RS),{param:"ids",flag:"--ids"},...se(gf),...se(PS),...se(hf),...se(yf),{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"}],ba=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...se(DS)],wa=[{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(ha),...se(_f),...se(NS),...se(hf),...se(yf),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],bf=[{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=se(bf),wf=[{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"}],va=se(wf),vf=[{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"}],Ea=se(vf),ka=[{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"}],Ta=se(ka),Sa=se(ka);var Aa=[{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}],xa=[{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]="21495fd2-6abb-5a4f-965c-e7b9c8f87dff")}catch{}})();function v(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Ef(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var U=v("id","item_id",!0),nr=v("id","item_id",!1),rr=v("text","string",!1),or=v("plan-id","item_id",!0),kf=v("step","string",!0),LS=["--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"],Ca=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],MS={"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."},yn=[{command:"plan create",parent:"plan",action:"create",slots:[v("title","string",!1,{polymorphic:!0})],accepted_flags:LS,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:[or],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:[or],accepted_flags:Ca,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(MS).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[or,kf],accepted_flags:Ca,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[or,kf,v("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:[or],accepted_flags:Ca,description:`${Ef(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:[v("kind","string",!0),...e==="list"?[]:[v("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Ef(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:[v("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:[v("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:[v("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:[v("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 snapshot create",parent:"workspace snapshot",action:"create",slots:[v("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:[v("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:[v("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:[v("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],FS=[...yn].sort((e,t)=>t.command.length-e.command.length),$S=new Map([["append",[U,rr]],["assurance",[v("action","action",!0),v("kind","string",!1),v("id","string",!1)]],["beads import",[v("file","string",!1)]],["changelog export",[v("file","string",!1)]],["claim",[nr]],["close",[U,rr]],["close-task",[U,v("reason","string",!1)]],["comments",[U,rr]],["completion",[v("shell","string",!1)]],["config",[v("scope","string",!1,{polymorphic:!0}),v("action","action",!1),v("key","string",!1),v("value","string",!1,{polymorphic:!0})]],["copy",[U]],["create",[v("type-or-title","string",!1,{polymorphic:!0}),v("title","string",!1)]],["delete",[U]],["deps",[U]],["docs",[U]],["event",[v("title","string",!0)]],["extension",[v("target","string",!1,{polymorphic:!0})]],["extension list",[]],["extension scaffold",[v("target","string",!0)]],["files",[U]],["files discover",[U]],["files lookup",[v("paths","string",!0,{variadic:!0})]],["focus",[nr]],["get",[U]],["graph",[v("subcommand","action",!0),nr,v("target","item_id",!1)]],["guide",[v("topic","string",!1)]],["history",[U]],["history-compact",[nr]],["history-redact",[U]],["history-repair",[nr]],["init",[v("prefix-or-path","string",!1,{polymorphic:!0})]],["install",[v("targets","string",!1,{variadic:!0})]],["item complete",[U,v("reason","string",!1)]],["item reopen",[U,v("reason","string",!0)]],["learnings",[U,rr]],["meet",[v("title","string",!0)]],["merge",[v("subcommand","action",!0),v("artifact","string",!1),v("base","string",!1),v("ours","string",!1),v("theirs","string",!1)]],["notes",[U,rr]],["package",[v("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[v("target","string",!0)]],["packages",[v("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[v("target","string",!0)]],["pause-task",[U]],["plan",[v("subcommand","action",!0),v("id","item_id",!1,{polymorphic:!0}),v("step","string",!1),v("new-order","integer",!1)]],["profile",[v("subcommand","action",!0),v("name","string",!1)]],["release",[U]],["remind",[v("title","string",!0)]],["restore",[U,v("target","string",!0)]],["schema",[v("subcommand","action",!0),v("name","string",!1)]],["search-advanced",[v("keywords","string",!0,{variadic:!0})]],["search",[v("keywords","string",!0,{variadic:!0})]],["start-task",[U]],["telemetry",[v("namespace-or-subcommand","action",!1,{polymorphic:!0}),v("subcommand","action",!1)]],["test",[U]],["update",[U]],["upgrade",[v("target","string",!1)]],["workspace snapshot",[v("action","action",!0),v("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("targets","string",!1,{variadic:!0})]])),["vcs abandon",[U]],["vcs create",[v("title","string",!0)]],["vcs merge",[U]],["vcs propose",[U]],["vcs ref-create",[v("name","string",!0)]],["vcs show",[U]]]);function jS(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function US(e){let t=jS(e);return FS.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 zS=[...$("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 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","package","consolidation","pm-tnud",["extension","extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension list","extension manage","extension migrate","extension reload","extension scaffold","extension uninstall","install","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","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",yn.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...$("plan","plan","target_noun","pm-pbyu",["plan"]),...$("plan","plan","target_noun","pm-2tan",yn.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"])],qS=[...new Set(zS.map(({command:e})=>e))].map(e=>({command:e,slots:US(e)?.slots??$S.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 Ia(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]="6664bc8f-e5da-5593-a2df-ac45f1cef09e")}catch{}})();var Tf=Ri.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),BS=[...Tf,{flag:"--version"}],Sf=[{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"}],Af=[{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"}],Uo=Pa([{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"},...Sf,{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"])),xf=[{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}],Cf=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function Pa(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var If=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note"]},{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:"--author"},{flag:"--message"},{flag:"--force"}],Of=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Rf=[{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"}],Nf=[{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"}],Df=[{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"}],Pf=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],Lf=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Mf=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Ff=[{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"}],$f=[{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"}],jf=[{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"}],Uf=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],La=[{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"}],zf=[{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"}],qf=[{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"}],Ma=[{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"}],tt=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],Bf=[...tt,{flag:"--capability"}],Oa=[...Ma,{flag:"--declarative"}],GS=[...Bf,{flag:"--declarative"}];var VS=[...tt,{flag:"--markdown"},{flag:"--output"}];var HS=[...tt,{flag:"--dry-run"}],WS=[...tt,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],KS=[...tt,{flag:"--watch"}],YS=[...tt,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],XS=[...tt,{flag:"--fields",list:!0}],JS=[...tt,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Gf=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Vf=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var Hf=[{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"}],Wf=[{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"},...Af,{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"}],Kf=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Yf=[{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"]}],Xf=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Jf=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Zf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Qf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],ep=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],tp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],np=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Fa=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...np],rp=Fa,op=[{flag:"--at"},{flag:"--text"},...np],ip=[{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"}],sp=[{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"}],ap=[{flag:"--limit"}],cp=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],lp=[{flag:"--dry-run"},{flag:"--scope"}],dp=[{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"}],up=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],fp=[{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"}],pp=[{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"}],$a=[{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"}],mp=[{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"}],_p=[{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"]}],Ra=[{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"},...mp,..._p,{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"}],yp=[{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"}],bp=[{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"}],wp=[{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"}],vp=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Ep=[{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,...mp,{flag:"--fixed_version"},..._p,{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"}],kp=[{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"},...Af,{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"}],Na=[{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"}],Tp=[{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"}],Sp=[{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"}],Da=Pa([{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"])),Ap=[{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"}],xp=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],Cp=[{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}],Ip=[{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"}],Op=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],et=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],Rp=[{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"]}],Np=Pa([{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"},...Sf],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Dp=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Pp=[{flag:"--eager-tags"}];var ZS=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],QS=Uo.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),eA=Uo.filter(e=>e.flag!=="--status");function ja(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 tA=ja(La),nA=ja($a),rA=new Map([["assurance",nA],["plan",tA],["workspace snapshot",ja(et)]]);function Lp(e=yn){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=rA.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 oA=Lp(),MV=new Map([["list",Uo],["list-all",eA],...ZS.map(e=>[e,QS]),["templates",Ra],["cal",Na],["ctx",Da],["test-runs-worker",cp],["init",zf],["config",qf],["extension",Ma],["package",Oa],["packages",Oa],["install",Gf],["upgrade",Vf],["create",Ra],["item mutate",hp],["item complete",yp],["item reopen",bp],["copy",wp],["focus",vp],["aggregate",xf],["calendar",Na],["context",Da],["get",Ap],["guide",xp],["search",Np],["next",Rp],["eval",Op],["workspace",et],["workspace snapshot",et],["workspace snapshot create",et],["workspace snapshot list",et],["workspace snapshot inspect",et],["workspace snapshot restore",et],["workspace snapshot delete",et],["history",Df],["history-redact",Lf],["history-repair",Mf],["history-author-acknowledge",Ff],["history-compact",$f],["merge",Pf],["schema",jf],["profile",Uf],["plan",La],["activity",Tp],["events",Sp],["restore",Xf],["update",Ep],["update-many",kp],["close",Hf],["close-many",Wf],["delete",Jf],["append",Kf],["comments",Cf],["notes",If],["learnings",Of],["files",Rf],["docs",Nf],["deps",Cp],["graph",Ip],["test",ip],["test-all",sp],["telemetry",ap],["health",fp],["assurance",$a],...oA,["validate",pp],["gc",lp],["stats",dp],["duplicates",up],["contracts",Dp],["completion",Pp],["claim",Yf],["release",Zf],["start-task",Qf],["pause-task",ep],["close-task",tp],["meet",Fa],["event",rp],["remind",op]]);(function(){try{var e=typeof window<"u"?window:typeof 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 Mp={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Fp={if:{required:["field"]}};Reflect.set(Fp,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var $p={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:[Fp],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:Mp,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:Mp,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]="2d43e788-cb8d-59b8-a447-4d24033bb55b")}catch{}})();var ir={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:to,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"},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"}},jp={assurance:{definition:$p,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}}},iA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Ua={subcommand:{type:"string",enum:[...iA]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...fc]},mode:{type:"string",enum:[...uc]},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:[...vr]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...pc]},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"]}},sr={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."},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"]}},Up={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."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},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."}},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]="b54b0565-3968-59ea-b5f9-8ae52731473a")}catch{}})();var aA=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],cA=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],lA=new Set(["action","cwd","options",...Object.keys(ir).filter(e=>e!=="severity")]);var dA={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"]},Vp=["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"],XV=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(ut.filter(e=>e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Ee(e){return Ia(e)}var uA=Ee([...va.map(e=>e.param),...jo.map(e=>e.param),"assignee","closeReason","completedAt"]),Hp=Ee([...Ea.map(e=>e.param),...jo.map(e=>e.param),"force"]),fA=Ee([...Ta.map(e=>e.param),...Hp.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),pA=Ee([...Sa.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),zp=Ee([...xa.map(e=>e.param),"past","section"]),mA=Ee([...Aa.map(e=>e.param),"stream"]),qa=Ee([...ya.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),bn=qa.filter(e=>e!=="all"&&e!=="status"),_A=qa.filter(e=>e!=="status"),bt=[[{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"}}]],gA=[[{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}}]],hA=Ee([...ba.map(e=>e.param),"count","completion","includeUnparented"]),yA=Ee(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...wa.map(e=>e.param)]),qp=Ee(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),me=["author","message","force"],Wp=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],ar=["author","assignee","message","force"],bA=["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 Bp(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:bA}}}var Gp={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},zo={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"]},...Bp("extension"),...Bp("package"),install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:{optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},create:{required:["title","description","type","status","priority","message"],optional:uA},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:qa,mutuallyExclusiveWhen:bt},"list-all":{optional:_A,mutuallyExclusiveWhen:bt},"list-draft":{optional:bn,mutuallyExclusiveWhen:bt},"list-open":{optional:bn,mutuallyExclusiveWhen:bt},"list-in-progress":{optional:bn,mutuallyExclusiveWhen:bt},"list-blocked":{optional:bn,mutuallyExclusiveWhen:bt},"list-closed":{optional:bn,mutuallyExclusiveWhen:bt},"list-canceled":{optional:bn,mutuallyExclusiveWhen:bt},aggregate:{optional:hA},guide:{optional:["list","format","depth"]},context:{optional:zp},ctx:{optional:zp},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:yA,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","snapshotAction"],optional:["name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"]},meet:Gp,event:Gp,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...qp,"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",...me],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...me],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",...me]},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",...Vp,"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",...me]},activity:{optional:mA},restore:{required:["id","target"],optional:me},update:{required:["id"],optional:Hp,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:fA,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...Wp,...me]},"close-many":{optional:pA},delete:{required:["id"],optional:["dryRun",...me]},append:{required:["id","body"],optional:me},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...me]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full",...me],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...me]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...me],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...me],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",...me],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:gA},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...qp,...ar],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:ar},"start-task":{required:["id"],optional:ar},"pause-task":{required:["id"],optional:ar},"close-task":{required:["id"],optional:["text","validateClose",...ar]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},wA=Object.freeze(Object.fromEntries(ut.map(e=>[e,zo[e]])));function Kp(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function vA(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=sr[e];return{...n,description:r?.description??Kp(e),...r?.examples?{examples:r.examples}:{}}}function EA(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=Up[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:sr[t]}function kA(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=EA(e,t);return{...r,description:o?.description??Kp(t),...o?.examples?{examples:o.examples}:{}}}function TA(e,t){let n=jp[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(Ua,t)?Ua[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:ir[t]}function SA(e,t){let n={action:{const:e,description:sr.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=TA(e,r);o&&(n[r]=kA(e,r,o))}return n}function AA(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 xA(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:Ee(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 Yp(e){if(!Object.prototype.hasOwnProperty.call(zo,e))return;let t=zo[e],n=dA[e]??[];return Ee(["action",...aA,...eo(e)!==void 0?cA:[],...n,...t.required??[],...t.optional??[]])}function CA(e){let t=zo[e],n=Ee(t.required??[]),r=Yp(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:SA(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=AA(e,t.oneOfRequired));let i=xA(t);return i.length>0&&(o.allOf=i),o}function Xp(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 Ba="4.9.0",Jp=Ba.split(".")[0],Zp="1.4.0",IA=Xp(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Jp}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Ba,type:"object",oneOf:ut.map(e=>CA(e))}));function OA(e,t){let n=vA(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 RA(){let e={action:{type:"string",description:sr.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(ir).sort())e[t]=OA(t,ir[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Zp,type:"object",additionalProperties:!1,required:["action"],properties:e}}var NA=Xp(RA);(function(){try{var e=typeof window<"u"?window:typeof 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 nH=new Set([...Fl,...$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]="c008aee5-ffe9-5da2-b1d9-6fb9fb6684c5")}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]="2a1e986f-304d-50f6-a405-6afc221bdad5")}catch{}})();var qA=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"]),c5=new Set([...qA].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 BA="2026-07-15T06:22:12.276Z",GA=Date.parse(BA),VA=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Qp=e=>typeof e=="string"?e:"",HA=e=>{let t=e??{},n=Qp(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(Qp(t.ts))>=GA);return VA[r][o]};function WA(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,m]of t.split(/\r?\n/).entries()){let _;try{_=JSON.parse(m)}catch{continue}l+=1;let g=HA(_);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 KA(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 em=async(e,t=20,n=!1)=>{let r=Va.join(e,"history"),o;try{o=(await Ga.readdir(r)).filter(E=>E.endsWith(".jsonl")).sort((E,k)=>E.localeCompare(k))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,m=0,_="_workspace.jsonl",g=new Set;if(o.includes(_))try{g=KA(await Ga.readFile(Va.join(r,_),"utf8"))}catch{g=new Set}for(let E of o){let k;try{k=await Ga.readFile(Va.join(r,E),"utf8")}catch{continue}let C=E.slice(0,-6),O=WA(C,k,t-s.length,g,n);c+=1,l+=O.checked_events,d+=O.unknown_event_count,u+=O.legacy_unknown_event_count,f+=O.actionable_unknown_event_count,m+=O.acknowledged_actionable_event_count,O.unknown_event_count>0&&i.add(C),s.push(...O.samples),n&&a.push(...O.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:m,affected_item_ids:[...i].sort((E,k)=>E.localeCompare(k)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import YA from"node:fs/promises";import Oe from"node:path";import XA 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]="1832e2b3-0ece-523d-8f38-598303d3f590")}catch{}})();var JA=["path","scope","note"],ZA=["pattern","glob","path","scope","note"],QA=["path"],ex=["from","to"],tx=new Set(["note","scope"]);function nm(e){let t=e??"project";if(!ci.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${ci.join(", ")} (default: project).`,h.USAGE);return t}function Wa(e){if(e.startsWith("```")||e.includes(`
|
|
111
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf("=");return t>=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(n=>n>=0&&n<t))?!1:e.includes("=")||ua(e)}function nx(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Wa(n)||!n.includes(",")?[t]:fa(n)})}function rx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function ox(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Wa(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&&rx(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 ix(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=ox(r);if(o!==void 0)return[o]}return nx([n]).map(o=>{let i=o.trim(),s=Wa(i)?gn(o,"--add"):{path:i};if(hn(s,"--add",JA),!s.path)throw new y(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return{path:s.path,scope:nm(s.scope),note:s.note?.trim()||void 0}})}):[]}function sx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--add-glob");hn(r,"--add-glob",ZA);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new y("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:o,scope:nm(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ax(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--remove"),o=Object.keys(r).filter(i=>tx.has(i.toLowerCase()));if(o.length>0)throw new y(`--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(hn(r,"--remove",QA),!r.path)throw new y("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function cx(e){return e?e.map(t=>{let n=gn(t,"--migrate");hn(n,"--migrate",ex);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new y("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:o}}):[]}function cr(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 lx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>cr(i.path,n))),o=[...new Set(t.map(i=>cr(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new y(`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 qo(e){return e.split(Oe.sep).join("/")}function Ha(e,t,n=process.cwd()){let r=e.trim();if(er(r))return r;if(Oe.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return qo(r.replaceAll("\\",Oe.sep));let o=Oe.relative(t,n);return o.startsWith(`..${Oe.sep}`)||o===".."||Oe.isAbsolute(o)?qo(Oe.normalize(r)):qo(Oe.relative(t,Oe.resolve(n,r)))}async function dx(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=Oe.isAbsolute(o.pattern),s=await XA(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Ha(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 ux(e,t,n){if(t===void 0)return e;if(!n)throw new y("--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 fx(e){return`${e.path}::${e.scope}`}function rm(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function om(e){return[...new Map(e.map(t=>[fx(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function px(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(er(a)){s.push(a.trim());continue}let c=Oe.isAbsolute(a)?a:Oe.resolve(t,a);try{(await YA.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&di(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 mx(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=cr(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=cr(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>cr(s,r)),count:o}}function _x(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=om(e);return r?o:rm(o)}async function tm(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?await px(t,e.workspaceRoot):void 0}}async function Bo(e,t,n,r){let{metadataKey:o}=r,i=tr(),s=oe(process.cwd(),n.path),a=Ci(s),c=process.cwd();await xe(s);let l=await Z(s),d=ae(l,G()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),m=await i.resolveList(t.remove,"--remove"),_=await i.resolveList(t.migrate,"--migrate"),g=ix(u,r.bareNoun).map(K=>({...K,path:Ha(K.path,a,c)})),b=sx(f),E=await dx(b,a,c),k=ux([...g,...E],t.note,g.length>0||b.length>0),C=ax(m).map(K=>Ha(K,a,c)),O=cx(_);if(lx(k,C,O),!(k.length>0||C.length>0||O.length>0)){let K=await Ue(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!K)throw new y(`Item ${e} not found`,h.NOT_FOUND);let Q=(await Ie(K,{schema:l.schema})).document.metadata[o]??[];return tm({id:K.id,artifacts:Q,changed:!1,options:t,workspaceRoot:a})}let L=Me(t.author,l.author_default),N=await Lo({pmRoot:s,settings:l,id:e,op:r.op,author:L,message:t.message,force:t.force,skipNoop:!0,mutate(K){let R=K.metadata,Q=R[o]??[],rc=[...Q],ur=mx(rc,k,C,O),Jo=_x(rc,ur.adds,ur.removes,r.supportsAppendStable&&t.appendStable===!0);Jo.length>0?R[o]=Jo:delete R[o];let oc=!Se(Q,Jo);return{changedFields:oc?[o]:[],warnings:oc&&ur.count>0?[`path_migrations_applied:${ur.count}`]:[]}}}),re=N.item[o]??[],W=N.warnings.find(K=>K.startsWith("path_migrations_applied:")),le=W?Number(W.slice(24)):0;return tm({id:N.item.id,artifacts:re,changed:N.changedFields.includes(o),migrationsApplied:le,options:t,workspaceRoot:a})}function Go(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 im(e,t,n){let r=await Bo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Go(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 sm(e,t,n){let r=await Bo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Go(r,"files")}import{readFileSync as gx}from"node:fs";import Vo 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 hx=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),lm=new Set(["--pm-path","--path","--author"]),yx={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"])},bx=new Set(["-p","--package"]),wx=new Set(["-c","--call"]),vx=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Ex=new Set(["-C","--prefix","--userconfig","--cache"]);var kx=new Set(["exec","x"]);function Tx(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Sx(e,t=process.cwd()){let n=Ax(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(am(r)||cm(r,t))return o;if(r==="node"&&o[0]&&cm(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?Ka(o):r==="pnpm"?Ix(o):r==="npm"?Ox(o):null;return i&&(am(i.command)||Cx(i.command))?i.args:null}var dm=(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 Tx(i)){let c=Sx(a),l=c?Rx(c):null,d=l&&hx.has(l.subcommand)?Nx(l.remaining,yx[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 Ax(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 am(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function xx(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 Cx(e){let t=xx(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function cm(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=Vo.resolve(t,e);try{return JSON.parse(gx(Vo.join(Vo.dirname(Vo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Ka(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(wx.has(r)){t+=1;break}t+=bx.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function um(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 Ix(e){let t=um(e,vx);return t?.subcommand!=="dlx"?null:Ka(t.args)}function Ox(e){let t=um(e,Ex);return!t||!kx.has(t.subcommand)?null:Ka(t.args)}function Rx(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(lm.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Nx(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("=")&&(lm.has(r)||t.has(r))&&(n+=1)}}import{execFile as Dx}from"node:child_process";import{readFile as Px}from"node:fs/promises";import Lx from"node:path";import{promisify as Mx}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 Fx=Mx(Dx),Ya=1,$x="linked-test-trust.json";function jx(e){return Lx.join(jr(e),$x)}function fm(){return{version:Ya,acknowledged:{}}}async function Ux(e){try{let t=JSON.parse(await Px(jx(e),"utf8"));return t.version!==Ya||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?fm():{version:Ya,acknowledged:t.acknowledged}}catch{return fm()}}async function pm(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 Fx("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 mm(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function zx(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Ne(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function lr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function qx(e){return Re(D({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 Bx(e,t,n){let r=qx(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||!zx(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...lr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...lr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...lr(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",...lr(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...lr(o,t)}}async function _m(e,t,n){let r=await Ux(e);return t.map(o=>Bx(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 gm(e){return e.includeBody?Po(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Jn(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]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var Gx=5;async function hm(e,t,n){let r=await Mo(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_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:Gx,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,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}},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 Xa(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 Vx(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function Hx(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 ym(e,t=Bt()){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=Vx(o.parent,n);s&&i.push(s),Hx(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function bm(e,t,n=Bt()){let r=aa(e,s=>t?_i(s,t):s==="closed"||s==="canceled",n),o=ym(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=>Xa(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]="aca69fd7-c47a-5424-b58f-f305f690edd9")}catch{}})();var Xx=["src","tests","docs"],Jx=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Zx=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Qx=["resolution","expected_result","actual_result"],eC=["default","tracked-all","tracked-all-strict"],wm=["core","strict","custom"],Ko=["off","warn","error"],Qa=["author","acceptance_criteria","estimated_minutes","close_reason"],Sm=[...Qa,"reviewer","risk","confidence","sprint","release"],nc=Array.from(new Set(Sm)),tC={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"},nC={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"},rC={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"},oC={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"},iC={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"},sC=32*1024*1024,aC=1e4,Am=40,Et=5,cC=4096,lC=255,dC=Yx(Kx);function xm(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?xm(r):r);return t}function uC(e){return{...e,checks:e.checks.map(t=>({...t,details:xm(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 Gt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function vm(e){return Gt(e).replace(/\/+$/,"")}function rt(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 Xo(e,t){return At(e,t)??e}function dr(e,t){return t.terminal_statuses.has(Xo(e,t))}function wt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ho(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function fC(e){let t=wt(ii),n={blocked_reason:wt(kt.blocked_reason),resolution:wt(kt.resolution),actual_result:wt(kt.actual_result)},r=wt(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:wt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:wt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:wt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ho(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:Ho(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ho(o.resolution,n.resolution)?"default":"settings",actual_result:Ho(o.actual_result,n.actual_result)?"default":"settings"}}}function pC(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(wm.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${wm.join(", ")}.`,h.USAGE)}function mC(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ko.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ko.join(", ")}.`,h.USAGE)}function _C(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ko.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ko.join(", ")}.`,h.USAGE)}function gC(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>tC[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function hC(e,t,n){let r=gC(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Qa],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Sm],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:[...Qa],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var yC=new Set(["acceptance_criteria","estimated_minutes"]);function bC(e,t,n,r){return!r&&yC.has(t)&&dr(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"?Xo(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 wC(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 y(`Unknown --scan-mode value "${e}". Supported values: ${eC.join(", ")}.`,h.USAGE)}function vC(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return _e.resolve(t);let n=_e.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return _e.dirname(_e.dirname(n));let o=_e.resolve(process.cwd()),i=Em(n),s=Em(o),a=_e.relative(i,s);return a.length===0||!a.startsWith("..")&&!_e.isAbsolute(a)?n:o}function Em(e){try{return Wx.native(e)}catch{return _e.resolve(e)}}function EC(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Cm(e,t,n){let r=t.length>0?_e.join(e,t):e,o;try{o=await tc.readdir(r,{withFileTypes:!0})}catch(i){if(te(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?_e.join(t,i.name):i.name;if(i.isDirectory()){if(Zx.has(i.name))continue;await Cm(e,s,n);continue}i.isFile()&&n.push(Gt(s))}}async function km(e){let t=[];for(let n of Xx)await Cm(e,n,t);for(let n of Jx){let r=_e.join(e,n);try{(await tc.stat(r)).isFile()&&t.push(Gt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function kC(e){try{let{stdout:t}=await dC("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:sC,windowsHide:!0,timeout:aC}),n=t.split("\0").map(r=>Gt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function TC(e,t){let n=new Set,r=vm(Vt);r.length>0&&n.add(r);let o=vm(_e.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function Tm(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function SC(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await kC(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await km(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await km(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function H(e,t=Et){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function vt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=H(e,Am);return{values:n.values,truncated:n.truncated,total:e.length}}var AC={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},xC={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function CC(e){let t=e.missing_fields.map(n=>`${AC[n]} "${xC[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function IC(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"):Ou(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 OC(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 RC="validate_metadata_duplicate_issue_codes";function NC(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Et,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:[`${RC}:${e.length}`]}}function DC(){return Object.fromEntries(nc.map(e=>[e,[]]))}function PC(e,t,n){let r=DC();for(let o of e)for(let i of nc)bC(o,i,t,n)&&r[i].push(o.id);return r}function LC(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${nC[o]}:${i.length}`)}return r.push(...n),r}function MC(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=rC[r];n[s]=i}return n}function FC(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 $C(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=oC[o],a=iC[o];if(!s||!a)continue;let c=H(i,r?i.length:Et);e[s]=c.values,e[a]=c.truncated}}function jC(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 UC(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 zC(e,t,n,r){let o=new Map(e.map(b=>[b.id,b])),i=t.profile==="strict",s=PC(e,n,i),a=Uu(e),c=NC(a,r),l=LC(t,s,c.warnings),d=MC(t,s),u=FC(t,s,o),f=zu(u),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:[...nc],counts:d,missing_by_type:f,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(m.configured_custom_required_fields=[...t.configured_custom_fields]),$C(m,t,s,r);let _=jC(t,s,o),g=UC(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:m},warnings:l,closeReasonBackfillRows:_,estimateBackfillRows:g}}function qC(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(Xo(f.status,t))),i=[],s=[];for(let f of o){let m=Qx.filter(_=>!de(f[_]));m.length!==0&&(i.push({id:f.id,missing_fields:m}),s.push({id:f.id,missing_fields:m,close_reason:de(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:Et,l=H(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>CC(f)),u=H(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 BC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function GC(e,t="pm",n=rn()){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=rt(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=rt(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>rt(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=rt(i.definition_of_ready);return HC(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function VC(e,t,n){let r=Xu(e,n?d=>dr(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:Et,a=H(o,s),c=H(i,s),l=H(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 HC(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${BC(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 WC(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,m)=>f.localeCompare(m)),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 KC(e,t="pm"){let n=GC(e,t),r=WC(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>Xa(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function YC(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 Yo(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function XC(e,t){let n=Yo(e).split("/").filter(Boolean),r=Yo(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function JC(e,t){let n=Yo(t),r=Yo(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=XC(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 ZC(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function QC(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=Gt(s.path);if(a.length===0||a===e)return;let c=JC(e,a);c!==null&&ZC(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 eI(e,t){return e.map(n=>{let r=YC(n),o=r==="docs_unowned"?"docs":"files",i=QC(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 tI(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function nI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=rt(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function rI(e,t,n,r,o){let i=rt(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&&!dr(s.status,o)}}function oI(e,t,n,r){let o=rt(e.blocked_by),i=rt(e.blocked_reason),s=i?.toLowerCase(),a=Xo(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 iI(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=>!dr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=nI(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=rt(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&dr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(rI(c,u,o,i,n))),t){let f=oI(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((m,_)=>m.localeCompare(_))})}}return a}function sI(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 Wo(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Ja(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function aI(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=Wo("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=Wo("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=Wo("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=Wo("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=Ja("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=Ja("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=Ja("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 cI(e){let t=Gt(e);return t.length>cC||t.split(/[\\/]/).some(n=>n.length>lC)}async function lI(e,t){let n=_e.isAbsolute(t)?t:_e.resolve(e,t);if(cI(n))return!1;try{let r=await tc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return EC(r,["ENOENT","ENOTDIR"])}}async function dI(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(er(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=Gt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await lI(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function uI(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:TC(t,n),d=l.length===0?[]:e.candidateFiles.filter(m=>Tm(m,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(m=>!Tm(m,l)),f={};if(d.length>0){let m=vt(d,i);f.pm_internals={count:d.length,paths:m.values,paths_truncated:m.truncated,paths_total:m.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function fI(e,t,n,r,o,i,s,a="pm"){let c=iI(e,t,o,i);sI(c);let l=KC(c.activeItems,a),d=bm(e,o),u=aI(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}),f=s?Number.POSITIVE_INFINITY:Et,m=H(c.closureLikeRows.map(N=>`${N.id}:${N.fields.join(",")}`),f),_=H(c.terminalParentRows.map(N=>`${N.id}:${N.parent_id}:${N.parent_status}`),f),g=H(c.staleBlockerRows.map(N=>`${N.id}:${N.status}:${N.reasons.join(",")}`),f),b=H(l.cycle_item_ids,f),E=H(l.cycle_sample_paths,f),k=H(d.cycle_item_ids,f),C=H(d.cycle_sample_paths,f),O=H(d.cardinality_violation_rows,f),A=H(d.parent_divergence_rows,f),L=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:L?"error":u.length===0?"ok":"warn",ok:!L&&u.length===0,details:{checked_active_items:c.activeItems.length,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:_.values,active_terminal_parent_rows_truncated:_.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:g.values,stale_blocker_rows_truncated:g.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:E.values,dependency_cycle_sample_paths_truncated:E.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:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:C.values,parent_cycle_sample_paths_truncated:C.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:O.values,hierarchy_cardinality_violation_rows_truncated:O.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:A.values,hierarchy_parent_divergence_rows_truncated:A.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:u,terminalParentFixRows:c.terminalParentFixRows}}async function pI(e,t,n,r,o,i){let s=await dI(e,t),a=new Map(e.map(R=>[R.id,R])),c=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),l=await SC(t,r),d=uI(l,n,t,r,o,i),u=d.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=eI(u,e),m=Gu(c,d.candidateFiles),_=new Map(m.map(R=>[R.path,R.classification])),g=m.filter(R=>R.classification==="moved").length,b=s.staleLinkRows.map(R=>({...R,classification:_.get(R.path)??"deleted"})).sort((R,Q)=>R.item_id.localeCompare(Q.item_id)||R.path.localeCompare(Q.path)||R.link_kind.localeCompare(Q.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 k=[...s.remoteLinkedPaths].sort((R,Q)=>R.localeCompare(Q)),C=vt(k,i),O=vt(c,i),A=vt(u,i),L=vt(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),i),N=i?f:vt(tI(f),!1).values,re=vt(Vu(m),i),W=b.map(R=>({item_id:R.item_id,path:R.path,link_kind:R.link_kind,classification:R.classification})),le=Wu(W,R=>{let Q=a.get(R);return Q?{type:Q.type,title:Q.title,status:Q.status}:void 0}),K=i?le:vt(Ku(le),!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:Am,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:k.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:O.total,missing_linked_paths:O.values,missing_linked_paths_truncated:O.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:re.values,missing_linked_path_classifications_truncated:re.truncated,missing_linked_path_rows_count:le.length,missing_linked_path_rows:K,orphaned_paths_count:u.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:L.values,orphaned_path_classifications_truncated:L.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:N}},warnings:E,staleLinkPruneRows:b}}function Im(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function mI(e,t,n){return`${e}:${t}:${Im(n)}`}function _I(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=Im(o.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function gI(e,t,n,r){let o=new Set(e.map(A=>A.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(A=>(A.tests??[]).map(L=>({item:A,linkedTest:L}))),d=await pm(mm()),u=await _m(r,l.map(({linkedTest:A})=>A),d),f=_I(l,u);for(let{item:A,linkedTest:L}of l){if(typeof L.command!="string"||L.command.trim().length===0)continue;i+=1;let N=dm(L.command,t);if(N.length!==0){s+=N.length;for(let re of N)a.add(re),o.has(re.toLowerCase())||c.push(mI(A.id,re,L.command))}}let m=[...new Set(c)].sort((A,L)=>A.localeCompare(L)),_=[...new Set(m.map(A=>A.split(":")[1]??""))].filter(A=>A.length>0).sort((A,L)=>A.localeCompare(L)),g=[];m.length>0&&g.push(`validate_command_references_stale_pm_ids:${m.length}`),f.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let b=n?Number.POSITIVE_INFINITY:Et,E=H(m,b),k=H(_,b),C=H([...a].sort((A,L)=>A.localeCompare(L)),b),O=H(f,b);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: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:O.values,untrusted_linked_tests_truncated:O.truncated,stale_pm_id_references_count:m.length,stale_pm_ids_count:_.length,stale_pm_ids:k.values,stale_pm_ids_truncated:k.truncated,stale_pm_id_reference_rows:E.values,stale_pm_id_reference_rows_truncated:E.truncated}},warnings:g}}function hI(e,t){let n=Dc(e.map(c=>({ref:c.id,version:Rc(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:Et,i=H(n.outdated,o),s=H(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:Rr,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 ec="pm validate auto-fix";async function yI(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:ec};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 y("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 Za(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function bI(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>Za(a)===null))try{await yI(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>Za(a)!==null)){let a=Za(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 sm(a.item_id,{remove:c,message:ec},t):await im(a.item_id,{remove:c,message:ec},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}async function wI(e,t,n,r){let o=await Zu(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:Ze(G())}),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 ef(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Vs(e,Eo(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await dn(e),d=l===null?null:await Hs(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await ln(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:f,lossless:m}=co(u);f.length>0&&i.push(`validate_merge_decisions_unreviewed:${f.length}`);let _=s>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:_,ok:_==="ok",details:{...o,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(g=>g.item_id))].sort((g,b)=>g.localeCompare(b)),lossless_merge_receipt_count:m.length,lossless_merge_receipt_items:[...new Set(m.map(g=>g.item_id))].sort((g,b)=>g.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 nt(e,t,n){n&&IC(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function vI(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=zC(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,nt(t,o,n)}if(e.requestedChecks.has("resolution")){let o=qC(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,nt(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=fI(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,nt(t,o,n),nt(t,VC(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await pI(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,nt(t,o,n)}return e.requestedChecks.has("command_references")&&nt(t,await gI(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&nt(t,await hm(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&nt(t,hI(e.items,r),n),e.requestedChecks.has("storage_integrity")&&nt(t,await wI(e.pmRoot,e.items,ae(e.settings,G()).type_to_folder,e.settings),n),t}function EI(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Du(t.closeReasonBackfillRows)),r.push(...Nu(t.resolutionBackfillRows)),r.push(...Pu(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Lu(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Mu(t.staleLinkPruneRows)),r}async function kI(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=EI(e,t,n),{applicable:a,gated:c}=$u(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await bI(a,o,i);d.push(...f.applied.map(Qn)),u.push(...f.failed.map(({fix:m,error:_})=>({...Qn(m),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,m)=>f.localeCompare(m)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Qn),applied_fixes:d,gated_fixes:c.map(f=>({...Qn(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Om(e,t,n={}){vl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--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 y("--fix-scope requires --auto-fix.",h.USAGE);let o=Fu(e.fixScope),i=oe(process.cwd(),t.path);await xe(i);let s=await Z(i),a=kn(s.schema),c=ae(s,G()),l=OC(e),d=[],u=await gm({includeBody:l.has("history_drift"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let W=await em(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",m=pC(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=hC(m,f,s.validation.metadata_required_fields),g=fC(s),b=mC(e.dependencyCycleSeverity),E=_C(e.parentCycleSeverity),k=wC(e.scanMode),C=vC(i),O=await vI({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:C,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:g,dependencyCycleSeverity:b,parentCycleSeverity:E,fileScanMode:k,initialWarnings:[...new Set(d)]}),A=r?await kI(e,O,s,o,t,n):void 0,L=[...new Set(O.warnings)].sort((W,le)=>W.localeCompare(le)),re={ok:!O.checks.some(W=>W.status==="error"),has_warnings:L.length>0,checks:O.checks,warnings:L,...A!==void 0?{fixes:A}:{},generated_at:z(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?re:{...uC(re),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]="c5620467-6c8c-5702-b742-57fba9e302c5")}catch{}})();async function TI(e,t){let n=e.dryRun===!0,r=await ln(process.cwd(),{includeLossless:!0}),{pendingDecisions:o}=co(r);if(!n&&e.force!==!0&&o.length>0)throw new y(`Merge reconciliation would accept ${o.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,h.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:o.map(b=>`Review receipt ${b.id} for ${b.item_id}: ${b.decisions.map(E=>E.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r.reduce((b,E)=>((b[E.item_id]??=[]).push(E),b),{}),s=Object.fromEntries(Object.entries(i).map(([b,E])=>[b,{merge:{receipts:E.map(Mt)}}])),a=await Iu({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:s},t),c=new Set(a.streams.map(b=>b.id)),l=Object.keys(i).filter(b=>!c.has(b));(await Promise.allSettled(l.map(b=>oa(b,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:s[b],forceAuditEntry:!0},t)))).forEach((b,E)=>{let k=l[E];if(b.status==="fulfilled"){let C=b.value.changed?"repaired":"skipped_clean";a.streams.push({id:k,outcome:C,entries_rehashed:b.value.history.entries_rehashed,entries_patch_repaired:b.value.history.entries_patch_repaired,reconciled_with_item:b.value.history.reconciled_with_item,warnings:b.value.warnings}),a.totals[C]+=1}else a.streams.push({id:k,outcome:"failed",error:b.reason instanceof Error?b.reason.message:String(b.reason)}),a.totals.failed+=1});let u=0;!n&&a.totals.failed===0&&(await Promise.all(r.map(b=>Ss(process.cwd(),b))),u=r.length);let f=await Om({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),m=f.checks.every(b=>b.status==="ok"),_=a.totals.failed===0&&m,g=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."]:_?["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:_,dry_run:n,repair:a,receipts:{pending_before:r.length,reconciled:u,summaries:r.map(Mt)},validation:f,guidance:g,generated_at:f.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]="687855bf-7432-5691-a809-1f0406b5d8a8")}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{ed as ITEM_LATEST_TIMESTAMP_FIELDS,Ql as ITEM_UNION_COLLECTION_FIELDS,Fs as MERGE_DRIVER_ARTIFACT_VALUES,Bs as PM_GITATTRIBUTES_END,Gn as PM_GITATTRIBUTES_START,bo as PM_GITATTRIBUTES_V2_END,zt as PM_GITATTRIBUTES_V2_START,Vs as auditMergeAttributeFence,Hs as auditMergeDriverConfiguration,vo as buildMergeAttributePatterns,dn as findGitWorkspaceRoot,kE as installMergeFence,ln as listMergeReceipts,Ss as markMergeReceiptReconciled,bs as mergeHistoryStreams,vs as mergeItemDocuments,Es as mergeJsonDocuments,ws as mergeRelationshipEventStreams,vE as refreshMergeAttributeFenceIfInstalled,zd as resolveMergeInstallContext,Eo as resolveProjectMergeTypeFolders,uE as runMergeDriver,EE as runMergeInstall,Aw as runMergeReceiptReport,TI as runMergeReconcile,Mt as summarizeMergeReceipt};
|
|
106
|
+
`)}function CS(e){let t=[],n="",r=!1,o=!1;for(let i of e){if(o){n+=i,o=!1;continue}if(i==="\\"){n+=i,o=!0;continue}if(i==='"'){r=!r,n+=i;continue}if(i===","&&!r){t.push(n.trim()),n="";continue}n+=i}return n.trim()&&t.push(n.trim()),t}function wf(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 IS(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 OS(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 RS(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=OS(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} ${_n} to read piped stdin input.`}function NS(e){let t=bf(e).trim();if(t.length===0||!t.includes(`
|
|
107
|
+
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=ba(t).split(`
|
|
108
|
+
`).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]=wf(s[3].trim()),r=a;continue}if(r&&yf.has(r.toLowerCase())){n[r]=`${n[r]}
|
|
109
|
+
${i}`;continue}return null}return n}function gn(e,t){let n=bf(e).trim();if(!n)throw new y(`${t} cannot be empty`,h.USAGE);let r=NS(n);if(r)return r;let o={},i,s=CS(n);for(let a of s){let c=IS(a);if(c>0){let l=a.slice(0,c).trim(),d=wf(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&yf.has(i.toLowerCase())){o[i]=`${o[i]},${a.trim()}`;continue}throw new y(RS(e,t),h.USAGE)}return o}var DS=/^[A-Za-z]:[\\/]/,PS=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function wa(e){let t=e.trim();return DS.test(t)?!1:PS.test(t)}function hn(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 y(`${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 y(`${t} provides key "${i}" more than once after case normalization.`,h.USAGE);e[s]=e[i],delete e[i]}}}async function LS(e){if(process.stdin.isTTY===!0)throw new y(`${e} value "${_n}" 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(ba(r))}),process.stdin.on("error",o=>{n(o)})})}function ar(){let e,t,n=async i=>{if(t&&t!==i)throw new y(`Only one option may use "${_n}" stdin token per command invocation. Already used by ${t}.`,h.USAGE);return t=i,e||(e=LS(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==_n?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()===_n?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new y(`${s} accepts "${_n}" 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]="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 MS={critical:0,high:1,medium:2,low:3,minimal:4},FS=Object.keys(MS),mz=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${FS.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 Rz=new Map(pi.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 rA}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 oA=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Fq=new RegExp(`\\b(${oA.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var $q=rA(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 zq=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]="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"}],Jq=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 iB=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 va(e,t){if(e==null)return[];let n=t?.separators??/,/,o=e.split(n).map(a=>a.trim()).filter(a=>a.length>0),s=t?.unique!==!1?Array.from(new Set(o)):o;return t?.sort===!0?[...s].sort():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]="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 yB 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 lA from"node:crypto";import Ea 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 DB=Ea.join("runtime","telemetry","events.jsonl"),PB=Ea.join("runtime","telemetry","state.json"),LB=Ea.join("runtime","telemetry","otel-spans.jsonl");var MB=3600*1e3;var FB=globalThis.fetch,dA=["user","automation","test","dogfood"],$B=Promise.resolve(),jB=Promise.resolve();var UB=new Set(dA);var zB=lA.randomUUID();var xf="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",qB=new RegExp(`\\b(${xf})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),BB=new RegExp(`(--${xf})(=|\\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]="be6f7869-f197-5d38-b8d9-faf8f390cd56")}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 ka=[{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}],Cf=ka.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),If=ka.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Ta=[{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}],Sa=Ta.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Of=Ta.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 ae(e){return e.map(t=>({...t}))}var Aa=[{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"}],Rf=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],vA=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Rf],Nf=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],EA=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],kA=[...Aa,...Nf],Df=[{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"}],TA=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Pf=[{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"}],xa=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...ae(Aa),...ae(vA),{param:"ids",flag:"--ids"},...ae(Nf),...ae(TA),...ae(Df),...ae(Pf),{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"}],Ca=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...ae(kA)],Ia=[{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"},...ae(Aa),...ae(Rf),...ae(EA),...ae(Df),...ae(Pf),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Lf=[{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"}],Vo=ae(Lf),Mf=[{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"}],Oa=ae(Mf),Ff=[{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"}],Ra=ae(Ff),Na=[{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"}],Da=ae(Na),Pa=ae(Na);var La=[{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}],Ma=[{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]="21495fd2-6abb-5a4f-965c-e7b9c8f87dff")}catch{}})();function E(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function $f(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var U=E("id","item_id",!0),cr=E("id","item_id",!1),lr=E("text","string",!1),dr=E("plan-id","item_id",!0),jf=E("step","string",!0),SA=["--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"],Fa=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],AA={"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."},yn=[{command:"plan create",parent:"plan",action:"create",slots:[E("title","string",!1,{polymorphic:!0})],accepted_flags:SA,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:[dr],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:[dr],accepted_flags:Fa,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(AA).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[dr,jf],accepted_flags:Fa,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[dr,jf,E("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:[dr],accepted_flags:Fa,description:`${$f(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:[E("kind","string",!0),...e==="list"?[]:[E("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${$f(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:[E("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:[E("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:[E("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:[E("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 snapshot create",parent:"workspace snapshot",action:"create",slots:[E("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:[E("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:[E("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:[E("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],xA=[...yn].sort((e,t)=>t.command.length-e.command.length),CA=new Map([["append",[U,lr]],["assurance",[E("action","action",!0),E("kind","string",!1),E("id","string",!1)]],["beads import",[E("file","string",!1)]],["changelog export",[E("file","string",!1)]],["claim",[cr]],["close",[U,lr]],["close-task",[U,E("reason","string",!1)]],["comments",[U,lr]],["completion",[E("shell","string",!1)]],["config",[E("scope","string",!1,{polymorphic:!0}),E("action","action",!1),E("key","string",!1),E("value","string",!1,{polymorphic:!0})]],["copy",[U]],["create",[E("type-or-title","string",!1,{polymorphic:!0}),E("title","string",!1)]],["delete",[U]],["deps",[U]],["docs",[U]],["event",[E("title","string",!0)]],["extension",[E("target","string",!1,{polymorphic:!0})]],["extension list",[]],["extension scaffold",[E("target","string",!0)]],["files",[U]],["files discover",[U]],["files lookup",[E("paths","string",!0,{variadic:!0})]],["focus",[cr]],["get",[U]],["graph",[E("subcommand","action",!0),cr,E("target","item_id",!1)]],["guide",[E("topic","string",!1)]],["history",[U]],["history-compact",[cr]],["history-redact",[U]],["history-repair",[cr]],["init",[E("prefix-or-path","string",!1,{polymorphic:!0})]],["install",[E("targets","string",!1,{variadic:!0})]],["item complete",[U,E("reason","string",!1)]],["item reopen",[U,E("reason","string",!0)]],["learnings",[U,lr]],["meet",[E("title","string",!0)]],["merge",[E("subcommand","action",!0),E("artifact","string",!1),E("base","string",!1),E("ours","string",!1),E("theirs","string",!1)]],["notes",[U,lr]],["package",[E("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[E("target","string",!0)]],["packages",[E("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[E("target","string",!0)]],["pause-task",[U]],["plan",[E("subcommand","action",!0),E("id","item_id",!1,{polymorphic:!0}),E("step","string",!1),E("new-order","integer",!1)]],["profile",[E("subcommand","action",!0),E("name","string",!1)]],["release",[U]],["remind",[E("title","string",!0)]],["restore",[U,E("target","string",!0)]],["schema",[E("subcommand","action",!0),E("name","string",!1)]],["search-advanced",[E("keywords","string",!0,{variadic:!0})]],["search",[E("keywords","string",!0,{variadic:!0})]],["start-task",[U]],["telemetry",[E("namespace-or-subcommand","action",!1,{polymorphic:!0}),E("subcommand","action",!1)]],["test",[U]],["update",[U]],["upgrade",[E("target","string",!1)]],["workspace snapshot",[E("action","action",!0),E("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[E("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[E("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[E("targets","string",!1,{variadic:!0})]])),["vcs abandon",[U]],["vcs create",[E("title","string",!0)]],["vcs merge",[U]],["vcs propose",[U]],["vcs ref-create",[E("name","string",!0)]],["vcs show",[U]]]);function IA(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function OA(e){let t=IA(e);return xA.find(n=>n.command===t||t.startsWith(`${n.command} `))}function F(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var RA=[...F("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...F("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"]),...F("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...F("list","list","target_noun","pm-pfqi",["list"]),...F("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...F("context","context","target_noun","pm-pbyu",["context"]),...F("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...F("search","search","target_noun","pm-pbyu",["search"]),...F("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...F("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...F("graph","graph","target_noun","pm-pbyu",["graph"]),...F("graph","graph show","consolidation","pm-yql1",["deps"]),...F("history","history","target_noun","pm-pbyu",["history"]),...F("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...F("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...F("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...F("workspace","workspace init","consolidation","pm-n7rr",["init"]),...F("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"]),...F("package","package","consolidation","pm-tnud",["extension","extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension list","extension manage","extension migrate","extension reload","extension scaffold","extension uninstall","install","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","upgrade"]),...F("package","package","package_owned","package:beads",["beads import"]),...F("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...F("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...F("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...F("ops","ops assurance","consolidation","pm-2tan",yn.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...F("plan","plan","target_noun","pm-pbyu",["plan"]),...F("plan","plan","target_noun","pm-2tan",yn.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...F("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...F("help","help","target_noun","pm-pbyu",["help"]),...F("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],NA=[...new Set(RA.map(({command:e})=>e))].map(e=>({command:e,slots:OA(e)?.slots??CA.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 $a(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]="6664bc8f-e5da-5593-a2df-ac45f1cef09e")}catch{}})();var Uf=Mi.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),DA=[...Uf,{flag:"--version"}],zf=[{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"}],qf=[{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"}],Ho=Ba([{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"},...zf,{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"])),Bf=[{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}],Gf=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function Ba(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var Vf=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note"]},{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:"--author"},{flag:"--message"},{flag:"--force"}],Hf=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Wf=[{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"}],Kf=[{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"}],Yf=[{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"}],Xf=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],Jf=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Zf=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Qf=[{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"}],ep=[{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"}],tp=[{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"}],np=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Ga=[{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"}],rp=[{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"}],op=[{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"}],Va=[{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"}],nt=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],ip=[...nt,{flag:"--capability"}],ja=[...Va,{flag:"--declarative"}],PA=[...ip,{flag:"--declarative"}];var LA=[...nt,{flag:"--markdown"},{flag:"--output"}];var MA=[...nt,{flag:"--dry-run"}],FA=[...nt,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],$A=[...nt,{flag:"--watch"}],jA=[...nt,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],UA=[...nt,{flag:"--fields",list:!0}],zA=[...nt,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],sp=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],ap=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var cp=[{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"}],lp=[{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"},...qf,{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"}],dp=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],up=[{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"]}],fp=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],pp=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],mp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],_p=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],gp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],hp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],yp=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Ha=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...yp],bp=Ha,wp=[{flag:"--at"},{flag:"--text"},...yp],vp=[{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"}],Ep=[{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"}],kp=[{flag:"--limit"}],Tp=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Sp=[{flag:"--dry-run"},{flag:"--scope"}],Ap=[{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"}],xp=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],Cp=[{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"}],Ip=[{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"}],Wa=[{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"}],Op=[{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"}],Rp=[{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"}],Np=[{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"]}],Ua=[{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"},...Op,...Rp,{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"}],Dp=[{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"}],Pp=[{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"}],Lp=[{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"}],Mp=[{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"}],Fp=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],$p=[{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"},...Np,...Op,{flag:"--fixed_version"},...Rp,{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"},...qf,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...Np,{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"}],za=[{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"}],Up=[{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"}],zp=[{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"}],qa=Ba([{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"])),qp=[{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"}],Bp=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],Gp=[{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}],Vp=[{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"}],Hp=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],tt=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],Wp=[{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"]}],Kp=Ba([{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"},...zf],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Yp=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Xp=[{flag:"--eager-tags"}];var qA=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],BA=Ho.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),GA=Ho.filter(e=>e.flag!=="--status");function Ka(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 VA=Ka(Ga),HA=Ka(Wa),WA=new Map([["assurance",HA],["plan",VA],["workspace snapshot",Ka(tt)]]);function Jp(e=yn){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=WA.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 KA=Jp(),UH=new Map([["list",Ho],["list-all",GA],...qA.map(e=>[e,BA]),["templates",Ua],["cal",za],["ctx",qa],["test-runs-worker",Tp],["init",rp],["config",op],["extension",Va],["package",ja],["packages",ja],["install",sp],["upgrade",ap],["create",Ua],["item mutate",Dp],["item complete",Pp],["item reopen",Lp],["copy",Mp],["focus",Fp],["aggregate",Bf],["calendar",za],["context",qa],["get",qp],["guide",Bp],["search",Kp],["next",Wp],["eval",Hp],["workspace",tt],["workspace snapshot",tt],["workspace snapshot create",tt],["workspace snapshot list",tt],["workspace snapshot inspect",tt],["workspace snapshot restore",tt],["workspace snapshot delete",tt],["history",Yf],["history-redact",Jf],["history-repair",Zf],["history-author-acknowledge",Qf],["history-compact",ep],["merge",Xf],["schema",tp],["profile",np],["plan",Ga],["activity",Up],["events",zp],["restore",fp],["update",$p],["update-many",jp],["close",cp],["close-many",lp],["delete",pp],["append",dp],["comments",Gf],["notes",Vf],["learnings",Hf],["files",Wf],["docs",Kf],["deps",Gp],["graph",Vp],["test",vp],["test-all",Ep],["telemetry",kp],["health",Cp],["assurance",Wa],...KA,["validate",Ip],["gc",Sp],["stats",Ap],["duplicates",xp],["contracts",Yp],["completion",Xp],["claim",up],["release",mp],["start-task",_p],["pause-task",gp],["close-task",hp],["meet",Ha],["event",bp],["remind",wp]]);(function(){try{var e=typeof window<"u"?window:typeof 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 Zp={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Qp={if:{required:["field"]}};Reflect.set(Qp,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var em={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:[Qp],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:Zp,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:Zp,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]="2d43e788-cb8d-59b8-a447-4d24033bb55b")}catch{}})();var ur={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:ao,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"},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"}},tm={assurance:{definition:em,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}}},YA=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Ya={subcommand:{type:"string",enum:[...YA]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...wc]},mode:{type:"string",enum:[...bc]},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:[...Cr]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...vc]},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"}}]}},Xa={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"]}},fr={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."},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"]}},nm={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."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},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."}},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]="b54b0565-3968-59ea-b5f9-8ae52731473a")}catch{}})();var JA=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],ZA=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],QA=new Set(["action","cwd","options",...Object.keys(ur).filter(e=>e!=="severity")]);var ex={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"]},am=["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"],e5=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(ft.filter(e=>e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function ke(e){return $a(e)}var tx=ke([...Oa.map(e=>e.param),...Vo.map(e=>e.param),"assignee","closeReason","completedAt"]),cm=ke([...Ra.map(e=>e.param),...Vo.map(e=>e.param),"force"]),nx=ke([...Da.map(e=>e.param),...cm.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),rx=ke([...Pa.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),rm=ke([...Ma.map(e=>e.param),"past","section"]),ox=ke([...La.map(e=>e.param),"stream"]),Ja=ke([...xa.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),bn=Ja.filter(e=>e!=="all"&&e!=="status"),ix=Ja.filter(e=>e!=="status"),vt=[[{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"}}]],sx=[[{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}}]],ax=ke([...Ca.map(e=>e.param),"count","completion","includeUnparented"]),cx=ke(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Ia.map(e=>e.param)]),om=ke(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),ge=["author","message","force"],lm=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],pr=["author","assignee","message","force"],lx=["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 im(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:lx}}}var sm={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},Wo={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"]},...im("extension"),...im("package"),install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:{optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},create:{required:["title","description","type","status","priority","message"],optional:tx},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Ja,mutuallyExclusiveWhen:vt},"list-all":{optional:ix,mutuallyExclusiveWhen:vt},"list-draft":{optional:bn,mutuallyExclusiveWhen:vt},"list-open":{optional:bn,mutuallyExclusiveWhen:vt},"list-in-progress":{optional:bn,mutuallyExclusiveWhen:vt},"list-blocked":{optional:bn,mutuallyExclusiveWhen:vt},"list-closed":{optional:bn,mutuallyExclusiveWhen:vt},"list-canceled":{optional:bn,mutuallyExclusiveWhen:vt},aggregate:{optional:ax},guide:{optional:["list","format","depth"]},context:{optional:rm},ctx:{optional:rm},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","snapshotAction"],optional:["name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"]},meet:sm,event:sm,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...om,"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",...am,"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:ox},restore:{required:["id","target"],optional:ge},update:{required:["id"],optional:cm,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:nx,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...lm,...ge]},"close-many":{optional:rx},delete:{required:["id"],optional:["dryRun",...ge]},append:{required:["id","body"],optional:ge},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...ge]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full",...ge],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...ge]},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:sx},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...om,...pr],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:pr},"start-task":{required:["id"],optional:pr},"pause-task":{required:["id"],optional:pr},"close-task":{required:["id"],optional:["text","validateClose",...pr]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},dx=Object.freeze(Object.fromEntries(ft.map(e=>[e,Wo[e]])));function dm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function ux(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=fr[e];return{...n,description:r?.description??dm(e),...r?.examples?{examples:r.examples}:{}}}function fx(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(Xa,t))return Xa[t];let n=nm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:fr[t]}function px(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=fx(e,t);return{...r,description:o?.description??dm(t),...o?.examples?{examples:o.examples}:{}}}function mx(e,t){let n=tm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(Ya,t)?Ya[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:ur[t]}function _x(e,t){let n={action:{const:e,description:fr.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=mx(e,r);o&&(n[r]=px(e,r,o))}return n}function gx(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 hx(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:ke(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 um(e){if(!Object.prototype.hasOwnProperty.call(Wo,e))return;let t=Wo[e],n=ex[e]??[];return ke(["action",...JA,...Ln(e)!==void 0?ZA:[],...n,...t.required??[],...t.optional??[]])}function yx(e){let t=Wo[e],n=ke(t.required??[]),r=um(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:_x(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=gx(e,t.oneOfRequired));let i=hx(t);return i.length>0&&(o.allOf=i),o}function fm(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 Za="4.9.0",pm=Za.split(".")[0],mm="1.4.0",bx=fm(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${pm}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Za,type:"object",oneOf:ft.map(e=>yx(e))}));function wx(e,t){let n=ux(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 vx(){let e={action:{type:"string",description:fr.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(ur).sort())e[t]=wx(t,ur[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":mm,type:"object",additionalProperties:!1,required:["action"],properties:e}}var Ex=fm(vx);(function(){try{var e=typeof window<"u"?window:typeof 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 s5=new Set([...Gl,...Vl]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c008aee5-ffe9-5da2-b1d9-6fb9fb6684c5")}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]="2a1e986f-304d-50f6-a405-6afc221bdad5")}catch{}})();var Nx=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"]),fW=new Set([...Nx].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 Dx="2026-07-15T06:22:12.276Z",Px=Date.parse(Dx),Lx=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],_m=e=>typeof e=="string"?e:"",Mx=e=>{let t=e??{},n=_m(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(_m(t.ts))>=Px);return Lx[r][o]};function Fx(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 g=Mx(_);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 $x(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 gm=async(e,t=20,n=!1)=>{let r=ec.join(e,"history"),o;try{o=(await Qa.readdir(r)).filter(T=>T.endsWith(".jsonl")).sort((T,k)=>T.localeCompare(k))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,_="_workspace.jsonl",g=new Set;if(o.includes(_))try{g=$x(await Qa.readFile(ec.join(r,_),"utf8"))}catch{g=new Set}for(let T of o){let k;try{k=await Qa.readFile(ec.join(r,T),"utf8")}catch{continue}let I=T.slice(0,-6),x=Fx(I,k,t-s.length,g,n);c+=1,l+=x.checked_events,d+=x.unknown_event_count,u+=x.legacy_unknown_event_count,f+=x.actionable_unknown_event_count,p+=x.acknowledged_actionable_event_count,x.unknown_event_count>0&&i.add(I),s.push(...x.samples),n&&a.push(...x.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((T,k)=>T.localeCompare(k)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import jx from"node:fs/promises";import Ne from"node:path";import Ux 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]="1832e2b3-0ece-523d-8f38-598303d3f590")}catch{}})();var zx=["path","scope","note"],qx=["pattern","glob","path","scope","note"],Bx=["path"],Gx=["from","to"],Vx=new Set(["note","scope"]);function ym(e){let t=e??"project";if(!mi.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${mi.join(", ")} (default: project).`,h.USAGE);return t}function nc(e){if(e.startsWith("```")||e.includes(`
|
|
110
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf("=");return t>=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(n=>n>=0&&n<t))?!1:e.includes("=")||wa(e)}function Hx(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||nc(n)||!n.includes(",")?[t]:va(n)})}function Wx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Kx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!nc(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&&Wx(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 Yx(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=Kx(r);if(o!==void 0)return[o]}return Hx([n]).map(o=>{let i=o.trim(),s=nc(i)?gn(o,"--add"):{path:i};if(hn(s,"--add",zx),!s.path)throw new y(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return{path:s.path,scope:ym(s.scope),note:s.note?.trim()||void 0}})}):[]}function Xx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--add-glob");hn(r,"--add-glob",qx);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new y("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:o,scope:ym(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Jx(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--remove"),o=Object.keys(r).filter(i=>Vx.has(i.toLowerCase()));if(o.length>0)throw new y(`--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(hn(r,"--remove",Bx),!r.path)throw new y("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function Zx(e){return e?e.map(t=>{let n=gn(t,"--migrate");hn(n,"--migrate",Gx);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new y("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:o}}):[]}function mr(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 Qx(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>mr(i.path,n))),o=[...new Set(t.map(i=>mr(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new y(`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 Ko(e){return e.split(Ne.sep).join("/")}function tc(e,t,n=process.cwd()){let r=e.trim();if(sr(r))return r;if(Ne.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Ko(r.replaceAll("\\",Ne.sep));let o=Ne.relative(t,n);return o.startsWith(`..${Ne.sep}`)||o===".."||Ne.isAbsolute(o)?Ko(Ne.normalize(r)):Ko(Ne.relative(t,Ne.resolve(n,r)))}async function eC(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=Ne.isAbsolute(o.pattern),s=await Ux(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>tc(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 tC(e,t,n){if(t===void 0)return e;if(!n)throw new y("--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 nC(e){return`${e.path}::${e.scope}`}function bm(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function wm(e){return[...new Map(e.map(t=>[nC(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function rC(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(sr(a)){s.push(a.trim());continue}let c=Ne.isAbsolute(a)?a:Ne.resolve(t,a);try{(await jx.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&kn(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 oC(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=mr(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=mr(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>mr(s,r)),count:o}}function iC(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=wm(e);return r?o:bm(o)}async function hm(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?await rC(t,e.workspaceRoot):void 0}}async function Yo(e,t,n,r){let{metadataKey:o}=r,i=ar(),s=ne(process.cwd(),n.path),a=Di(s),c=process.cwd();await Ie(s);let l=await Z(s),d=le(l,V()),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"),g=Yx(u,r.bareNoun).map(Y=>({...Y,path:tc(Y.path,a,c)})),b=Xx(f),T=await eC(b,a,c),k=tC([...g,...T],t.note,g.length>0||b.length>0),I=Jx(p).map(Y=>tc(Y,a,c)),x=Zx(_);if(Qx(k,I,x),!(k.length>0||I.length>0||x.length>0)){let Y=await ze(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!Y)throw new y(`Item ${e} not found`,h.NOT_FOUND);let z=(await Re(Y,{schema:l.schema})).document.metadata[o]??[];return hm({id:Y.id,artifacts:z,changed:!1,options:t,workspaceRoot:a})}let N=Fe(t.author,l.author_default),P=await zo({pmRoot:s,settings:l,id:e,op:r.op,author:N,message:t.message,force:t.force,skipNoop:!0,mutate(Y){let D=Y.metadata,z=D[o]??[],hr=[...z],yr=oC(hr,k,I,x),ri=iC(hr,yr.adds,yr.removes,r.supportsAppendStable&&t.appendStable===!0);ri.length>0?D[o]=ri:delete D[o];let fc=!Ae(z,ri);return{changedFields:fc?[o]:[],warnings:fc&&yr.count>0?[`path_migrations_applied:${yr.count}`]:[]}}}),ie=P.item[o]??[],Q=P.warnings.find(Y=>Y.startsWith("path_migrations_applied:")),fe=Q?Number(Q.slice(24)):0;return hm({id:P.item.id,artifacts:ie,changed:P.changedFields.includes(o),migrationsApplied:fe,options:t,workspaceRoot:a})}function Xo(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 vm(e,t,n){let r=await Yo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Xo(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 Em(e,t,n){let r=await Yo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Xo(r,"files")}import{readFileSync as sC}from"node:fs";import Jo 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"]),Sm=new Set(["--pm-path","--path","--author"]),cC={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"])},lC=new Set(["-p","--package"]),dC=new Set(["-c","--call"]),uC=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),fC=new Set(["-C","--prefix","--userconfig","--cache"]);var pC=new Set(["exec","x"]);function mC(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function _C(e,t=process.cwd()){let n=gC(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(km(r)||Tm(r,t))return o;if(r==="node"&&o[0]&&Tm(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?rc(o):r==="pnpm"?bC(o):r==="npm"?wC(o):null;return i&&(km(i.command)||yC(i.command))?i.args:null}var Am=(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 mC(i)){let c=_C(a),l=c?vC(c):null,d=l&&aC.has(l.subcommand)?EC(l.remaining,cC[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 gC(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 km(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function hC(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 yC(e){let t=hC(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Tm(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=Jo.resolve(t,e);try{return JSON.parse(sC(Jo.join(Jo.dirname(Jo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function rc(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(dC.has(r)){t+=1;break}t+=lC.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function xm(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 bC(e){let t=xm(e,uC);return t?.subcommand!=="dlx"?null:rc(t.args)}function wC(e){let t=xm(e,fC);return!t||!pC.has(t.subcommand)?null:rc(t.args)}function vC(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Sm.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function EC(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("=")&&(Sm.has(r)||t.has(r))&&(n+=1)}}import{execFile as kC}from"node:child_process";import{readFile as TC}from"node:fs/promises";import SC from"node:path";import{promisify as AC}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 xC=AC(kC),oc=1,CC="linked-test-trust.json";function IC(e){return SC.join(Hr(e),CC)}function Cm(){return{version:oc,acknowledged:{}}}async function OC(e){try{let t=JSON.parse(await TC(IC(e),"utf8"));return t.version!==oc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Cm():{version:oc,acknowledged:t.acknowledged}}catch{return Cm()}}async function Im(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 xC("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 Om(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function RC(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&De(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function _r(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function NC(e){return ce(O({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 DC(e,t,n){let r=NC(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||!RC(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",..._r(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",..._r(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",..._r(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",..._r(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",..._r(o,t)}}async function Rm(e,t,n){let r=await OC(e);return t.map(o=>DC(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 Nm(e){return e.includeBody?Uo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):rr(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]="a1261d65-222c-5c6c-8634-a4413a91aba9")}catch{}})();var PC=5;async function Dm(e,t,n){let r=await qo(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_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:PC,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,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}},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 ic(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 LC(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function MC(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 Pm(e,t=Gt()){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=LC(o.parent,n);s&&i.push(s),MC(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function Lm(e,t,n=Gt()){let r=ga(e,s=>t?wi(s,t):s==="closed"||s==="canceled",n),o=Pm(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=>ic(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]="3d7d6f15-7587-5c22-8deb-373bfd063d2b")}catch{}})();var UC=["src","tests","docs"],zC=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],qC=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),BC=["resolution","expected_result","actual_result"],GC=["default","tracked-all","tracked-all-strict"],Mm=["core","strict","custom"],ei=["off","warn","error"],cc=["author","acceptance_criteria","estimated_minutes","close_reason"],zm=[...cc,"reviewer","risk","confidence","sprint","release"],uc=Array.from(new Set(zm)),VC={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"},HC={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"},WC={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"},KC={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"},YC={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"},XC=32*1024*1024,JC=1e4,qm=40,Tt=5,ZC=4096,QC=255,eI=jC($C);function Bm(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Bm(r):r);return t}function tI(e){return{...e,checks:e.checks.map(t=>({...t,details:Bm(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 Vt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Fm(e){return Vt(e).replace(/\/+$/,"")}function ot(e){let t=ue(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function ni(e,t){return Ct(e,t)??e}function gr(e,t){return t.terminal_statuses.has(ni(e,t))}function Et(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Zo(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function nI(e){let t=Et(ui),n={blocked_reason:Et(St.blocked_reason),resolution:Et(St.resolution),actual_result:Et(St.actual_result)},r=Et(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:Et(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Et(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Et(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Zo(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:Zo(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Zo(o.resolution,n.resolution)?"default":"settings",actual_result:Zo(o.actual_result,n.actual_result)?"default":"settings"}}}function rI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Mm.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${Mm.join(", ")}.`,h.USAGE)}function oI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ei.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ei.join(", ")}.`,h.USAGE)}function iI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ei.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ei.join(", ")}.`,h.USAGE)}function sI(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>VC[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:[...cc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...zm],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:[...cc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var cI=new Set(["acceptance_criteria","estimated_minutes"]);function lI(e,t,n,r){return!r&&cI.has(t)&&gr(e.status,n)?!1:t==="author"?!ue(e.author):t==="acceptance_criteria"?!ue(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?ni(e.status,n)===n.close_status&&!ue(e.close_reason):t==="reviewer"?!ue(e.reviewer):t==="risk"?!ue(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ue(e.confidence):t==="sprint"?!ue(e.sprint):!ue(e.release)}function dI(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 y(`Unknown --scan-mode value "${e}". Supported values: ${GC.join(", ")}.`,h.USAGE)}function uI(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=$m(n),s=$m(o),a=he.relative(i,s);return a.length===0||!a.startsWith("..")&&!he.isAbsolute(a)?n:o}function $m(e){try{return FC.native(e)}catch{return he.resolve(e)}}function fI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Gm(e,t,n){let r=t.length>0?he.join(e,t):e,o;try{o=await dc.readdir(r,{withFileTypes:!0})}catch(i){if(te(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(qC.has(i.name))continue;await Gm(e,s,n);continue}i.isFile()&&n.push(Vt(s))}}async function jm(e){let t=[];for(let n of UC)await Gm(e,n,t);for(let n of zC){let r=he.join(e,n);try{(await dc.stat(r)).isFile()&&t.push(Vt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function pI(e){try{let{stdout:t}=await eI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:XC,windowsHide:!0,timeout:JC}),n=t.split("\0").map(r=>Vt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function mI(e,t){let n=new Set,r=Fm(Ht);r.length>0&&n.add(r);let o=Fm(he.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function Um(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function _I(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await pI(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await jm(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await jm(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function W(e,t=Tt){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function kt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=W(e,qm);return{values:n.values,truncated:n.truncated,total:e.length}}var gI={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},hI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function yI(e){let t=e.missing_fields.map(n=>`${gI[n]} "${hI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function bI(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"):Hu(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 wI(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 vI="validate_metadata_duplicate_issue_codes";function EI(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Tt,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:[`${vI}:${e.length}`]}}function kI(){return Object.fromEntries(uc.map(e=>[e,[]]))}function TI(e,t,n){let r=kI();for(let o of e)for(let i of uc)lI(o,i,t,n)&&r[i].push(o.id);return r}function SI(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${HC[o]}:${i.length}`)}return r.push(...n),r}function AI(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=WC[r];n[s]=i}return n}function xI(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 CI(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=KC[o],a=YC[o];if(!s||!a)continue;let c=W(i,r?i.length:Tt);e[s]=c.values,e[a]=c.truncated}}function II(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:ue(n.get(o)?.resolution)})):[]}function OI(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:ue(n.get(o)?.type)})):[]}function RI(e,t,n,r){let o=new Map(e.map(b=>[b.id,b])),i=t.profile==="strict",s=TI(e,n,i),a=nf(e),c=EI(a,r),l=SI(t,s,c.warnings),d=AI(t,s),u=xI(t,s,o),f=rf(u),p={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:[...uc],counts:d,missing_by_type:f,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),CI(p,t,s,r);let _=II(t,s,o),g=OI(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:p},warnings:l,closeReasonBackfillRows:_,estimateBackfillRows:g}}function NI(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(ni(f.status,t))),i=[],s=[];for(let f of o){let p=BC.filter(_=>!ue(f[_]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:ue(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:Tt,l=W(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>yI(f)),u=W(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 DI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PI(e,t="pm",n=on()){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=ot(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=ot(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>ot(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=ot(i.definition_of_ready);return MI(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function LI(e,t,n){let r=pf(e,n?d=>gr(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:Tt,a=W(o,s),c=W(i,s),l=W(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 MI(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${DI(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 FI(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 $I(e,t="pm"){let n=PI(e,t),r=FI(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>ic(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function jI(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 ti(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function UI(e,t){let n=ti(e).split("/").filter(Boolean),r=ti(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function zI(e,t){let n=ti(t),r=ti(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=UI(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 qI(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function BI(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=Vt(s.path);if(a.length===0||a===e)return;let c=zI(e,a);c!==null&&qI(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 GI(e,t){return e.map(n=>{let r=jI(n),o=r==="docs_unowned"?"docs":"files",i=BI(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 VI(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function HI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=ot(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function WI(e,t,n,r,o){let i=ot(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&&!gr(s.status,o)}}function KI(e,t,n,r){let o=ot(e.blocked_by),i=ot(e.blocked_reason),s=i?.toLowerCase(),a=ni(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 YI(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=>!gr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=HI(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=ot(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&gr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(WI(c,u,o,i,n))),t){let f=KI(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 XI(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 Qo(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function sc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function JI(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=Qo("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=Qo("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=Qo("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=Qo("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=sc("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=sc("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=sc("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 ZI(e){let t=Vt(e);return t.length>ZC||t.split(/[\\/]/).some(n=>n.length>QC)}async function QI(e,t){let n=he.isAbsolute(t)?t:he.resolve(e,t);if(ZI(n))return!1;try{let r=await dc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return fI(r,["ENOENT","ENOTDIR"])}}async function eO(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(sr(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=Vt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await QI(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function tO(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:mI(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>Um(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!Um(p,l)),f={};if(d.length>0){let p=kt(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 nO(e,t,n,r,o,i,s,a="pm"){let c=YI(e,t,o,i);XI(c);let l=$I(c.activeItems,a),d=Lm(e,o),u=JI(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}),f=s?Number.POSITIVE_INFINITY:Tt,p=W(c.closureLikeRows.map(P=>`${P.id}:${P.fields.join(",")}`),f),_=W(c.terminalParentRows.map(P=>`${P.id}:${P.parent_id}:${P.parent_status}`),f),g=W(c.staleBlockerRows.map(P=>`${P.id}:${P.status}:${P.reasons.join(",")}`),f),b=W(l.cycle_item_ids,f),T=W(l.cycle_sample_paths,f),k=W(d.cycle_item_ids,f),I=W(d.cycle_sample_paths,f),x=W(d.cardinality_violation_rows,f),v=W(d.parent_divergence_rows,f),N=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:N?"error":u.length===0?"ok":"warn",ok:!N&&u.length===0,details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:_.values,active_terminal_parent_rows_truncated:_.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:g.values,stale_blocker_rows_truncated:g.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:T.values,dependency_cycle_sample_paths_truncated:T.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:k.values,parent_cycle_item_ids_truncated:k.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:v.values,hierarchy_parent_divergence_rows_truncated:v.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:u,terminalParentFixRows:c.terminalParentFixRows}}async function rO(e,t,n,r,o,i){let s=await eO(e,t),a=new Map(e.map(D=>[D.id,D])),c=[...new Set(s.missingLinkedPaths)].sort((D,z)=>D.localeCompare(z)),l=await _I(t,r),d=tO(l,n,t,r,o,i),u=d.candidateFiles.filter(D=>!s.linkedProjectPaths.has(D)),f=GI(u,e),p=af(c,d.candidateFiles),_=new Map(p.map(D=>[D.path,D.classification])),g=p.filter(D=>D.classification==="moved").length,b=s.staleLinkRows.map(D=>({...D,classification:_.get(D.path)??"deleted"})).sort((D,z)=>D.item_id.localeCompare(z.item_id)||D.path.localeCompare(z.path)||D.link_kind.localeCompare(z.link_kind)),T=[];d.strictModeForcesPmInternals&&T.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&T.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&T.push(`validate_files_orphaned_paths:${u.length}`);let k=[...s.remoteLinkedPaths].sort((D,z)=>D.localeCompare(z)),I=kt(k,i),x=kt(c,i),v=kt(u,i),N=kt(f.map(D=>`${D.path}:${D.classification}:owner_candidate=${D.owner_candidate?.id??"unowned"}`),i),P=i?f:kt(VI(f),!1).values,ie=kt(cf(p),i),Q=b.map(D=>({item_id:D.item_id,path:D.path,link_kind:D.link_kind,classification:D.classification})),fe=df(Q,D=>{let z=a.get(D);return z?{type:z.type,title:z.title,status:z.status}:void 0}),Y=i?fe:kt(uf(fe),!1).values;return{check:{name:"files",status:T.length===0?"ok":"warn",ok:T.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:qm,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:k.length,remote_linked_paths_total:I.total,remote_linked_paths:I.values,remote_linked_paths_truncated:I.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:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:ie.values,missing_linked_path_classifications_truncated:ie.truncated,missing_linked_path_rows_count:fe.length,missing_linked_path_rows:Y,orphaned_paths_count:u.length,orphaned_paths_total:v.total,orphaned_paths:v.values,orphaned_paths_truncated:v.truncated,orphaned_path_classifications:N.values,orphaned_path_classifications_truncated:N.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:P}},warnings:T,staleLinkPruneRows:b}}function Vm(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function oO(e,t,n){return`${e}:${t}:${Vm(n)}`}function iO(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=Vm(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(v=>v.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(v=>(v.tests??[]).map(N=>({item:v,linkedTest:N}))),d=await Im(Om()),u=await Rm(r,l.map(({linkedTest:v})=>v),d),f=iO(l,u);for(let{item:v,linkedTest:N}of l){if(typeof N.command!="string"||N.command.trim().length===0)continue;i+=1;let P=Am(N.command,t);if(P.length!==0){s+=P.length;for(let ie of P)a.add(ie),o.has(ie.toLowerCase())||c.push(oO(v.id,ie,N.command))}}let p=[...new Set(c)].sort((v,N)=>v.localeCompare(N)),_=[...new Set(p.map(v=>v.split(":")[1]??""))].filter(v=>v.length>0).sort((v,N)=>v.localeCompare(N)),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 b=n?Number.POSITIVE_INFINITY:Tt,T=W(p,b),k=W(_,b),I=W([...a].sort((v,N)=>v.localeCompare(N)),b),x=W(f,b);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:I.values,unique_referenced_pm_ids_truncated:I.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:x.values,untrusted_linked_tests_truncated:x.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:_.length,stale_pm_ids:k.values,stale_pm_ids_truncated:k.truncated,stale_pm_id_reference_rows:T.values,stale_pm_id_reference_rows_truncated:T.truncated}},warnings:g}}function aO(e,t){let n=Uc(e.map(c=>({ref:c.id,version:$c(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:Tt,i=W(n.outdated,o),s=W(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:$r,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 lc="pm validate auto-fix";async function cO(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:lc};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 y("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 ac(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function lO(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>ac(a)===null))try{await cO(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>ac(a)!==null)){let a=ac(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 Em(a.item_id,{remove:c,message:lc},t):await vm(a.item_id,{remove:c,message:lc},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}function dO(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function uO(e,t,n,r){let o=await _f(e,new Set(t.map(b=>b.id)),n,{schema:r.schema,extensionFieldNames:Qe(V())}),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 hf(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ea(e,Co(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await yt(e),d=l===null?null:await ta(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await Gn(l??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:_}=_o(f);p.length>0&&i.push(`validate_merge_decisions_unreviewed:${p.length}`),dO(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(b=>b.item_id))].sort((b,T)=>b.localeCompare(T)),lossless_merge_receipt_count:_.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(_.map(b=>b.item_id))].sort((b,T)=>b.localeCompare(T)),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 rt(e,t,n){n&&bI(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function fO(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=RI(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,rt(t,o,n)}if(e.requestedChecks.has("resolution")){let o=NI(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,rt(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=nO(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,rt(t,o,n),rt(t,LI(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await rO(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,rt(t,o,n)}return e.requestedChecks.has("command_references")&&rt(t,await sO(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&rt(t,await Dm(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&rt(t,aO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&rt(t,await uO(e.pmRoot,e.items,le(e.settings,V()).type_to_folder,e.settings),n),t}function pO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Yu(t.closeReasonBackfillRows)),r.push(...Ku(t.resolutionBackfillRows)),r.push(...Xu(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Ju(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Zu(t.staleLinkPruneRows)),r}async function mO(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=pO(e,t,n),{applicable:a,gated:c}=ef(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await lO(a,o,i);d.push(...f.applied.map(ir)),u.push(...f.failed.map(({fix:p,error:_})=>({...ir(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(ir),applied_fixes:d,gated_fixes:c.map(f=>({...ir(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Hm(e,t,n={}){Cl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--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 y("--fix-scope requires --auto-fix.",h.USAGE);let o=Qu(e.fixScope),i=ne(process.cwd(),t.path);await Ie(i);let s=await Z(i),a=Sn(s.schema),c=le(s,V()),l=wI(e),d=[],u=await Nm({includeBody:l.has("history_drift"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let Q=await gm(i);Q.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${Q.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=rI(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=aI(p,f,s.validation.metadata_required_fields),g=nI(s),b=oI(e.dependencyCycleSeverity),T=iI(e.parentCycleSeverity),k=dI(e.scanMode),I=uI(i),x=await fO({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:I,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:g,dependencyCycleSeverity:b,parentCycleSeverity:T,fileScanMode:k,initialWarnings:[...new Set(d)]}),v=r?await mO(e,x,s,o,t,n):void 0,N=[...new Set(x.warnings)].sort((Q,fe)=>Q.localeCompare(fe)),ie={ok:!x.checks.some(Q=>Q.status==="error"),has_warnings:N.length>0,checks:x.checks,warnings:N,...v!==void 0?{fixes:v}:{},generated_at:q(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?ie:{...tI(ie),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 Wm=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]="c3ec7d9d-f276-5e97-8e97-507925e5d33a")}catch{}})();var _O=4;async function gO(e){try{return{status:"fulfilled",value:await pa(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 hO(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 yO(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=>Ps(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function bO(e,t){let n=e.dryRun===!0,r=ne(process.cwd(),t.path),o=await yt(r),i=await Gn(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(i.invalid_evidence_count>0)throw new y(`Merge reconciliation refused ${i.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 s=i.receipts,{pendingDecisions:a}=_o(s);if(!n&&e.force!==!0&&a.length>0)throw new y(`Merge reconciliation would accept ${a.length} receipt(s) containing discarded scalar values. Review pm merge report and rerun with --force only after deciding which values to retain or re-apply.`,h.CONFLICT,{code:"merge_reconcile_discards_require_acceptance",required:"Explicitly review every discarded field before accepting reconciliation.",nextSteps:a.map(v=>`Review receipt ${v.id} for ${v.item_id}: ${v.decisions.map(N=>N.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let c=new Map;for(let v of s){let N=c.get(v.item_id)??[];N.push(v),c.set(v.item_id,N)}let l=Object.fromEntries([...c].map(([v,N])=>[v,{merge:{receipts:N.map(Ve)}}])),d=Object.fromEntries([...c].map(([v,N])=>[v,{gitWorkspaceRoot:o,receipts:N}])),u=await Vu({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:l,...s.length>0?{mergeReceiptProofById:d}:{}},t),f=new Set(u.streams.map(v=>v.id)),p=[...c.keys()].filter(v=>!f.has(v)),_=await Wm(p,_O,v=>gO({id:v,dryRun:n,options:e,global:t,auditContext:l[v],mergeReceiptProof:d[v]}));hO({receiptOnlyIds:p,results:_,repair:u});let g=await yO({dryRun:n,force:e.force===!0,pendingReceipts:s,repair:u,gitWorkspaceRoot:o}),b=await Hm({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),T=b.checks.every(v=>v.status==="ok"),k=n?s.length===0:g===s.length,I=u.totals.failed===0&&T&&k,x=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."]:I?["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:I,dry_run:n,repair:u,receipts:{pending_before:s.length,reconciled:g,summaries:s.map(Ve)},validation:b,guidance:x,generated_at:b.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]="687855bf-7432-5691-a809-1f0406b5d8a8")}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{ld as ITEM_LATEST_TIMESTAMP_FIELDS,cd as ITEM_UNION_COLLECTION_FIELDS,Hs as MERGE_DRIVER_ARTIFACT_VALUES,Zs as PM_GITATTRIBUTES_END,Xn as PM_GITATTRIBUTES_START,So as PM_GITATTRIBUTES_V2_END,qt as PM_GITATTRIBUTES_V2_START,ea as auditMergeAttributeFence,ta as auditMergeDriverConfiguration,xo as buildMergeAttributePatterns,yt as findGitWorkspaceRoot,ck as installMergeFence,kd as listMergeReceipts,Ps as markMergeReceiptReconciled,Ss as mergeHistoryStreams,xs as mergeItemDocuments,Cs as mergeJsonDocuments,As as mergeRelationshipEventStreams,sk as refreshMergeAttributeFenceIfInstalled,nu as resolveMergeInstallContext,Co as resolveProjectMergeTypeFolders,XE as runMergeDriver,ak as runMergeInstall,uv as runMergeReceiptReport,bO as runMergeReconcile,Ve as summarizeMergeReceipt};
|
|
112
111
|
//# sourceMappingURL=sdk-merge.js.map
|