@unbrained/pm-cli 2026.8.16 → 2026.8.17
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 +30 -3
- package/README.md +13 -13
- package/dist/cli/public.d.ts +2 -0
- package/dist/cli/public.js +21 -0
- package/dist/cli/register-mutation.js +4 -4
- package/dist/cli-bundle/bundle-manifest.json +151 -151
- package/dist/cli-bundle/chunks/{chunk-I2LUWWR5.js → chunk-2QLOXC3V.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-URW4QRMI.js → chunk-3UEGXBMR.js} +22 -22
- package/dist/cli-bundle/chunks/chunk-4JPYF536.js +35 -0
- package/dist/cli-bundle/chunks/chunk-6VDLG2FC.js +13 -0
- package/dist/cli-bundle/chunks/chunk-7IBRGCHX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-HBJAS566.js +8 -0
- package/dist/cli-bundle/chunks/chunk-ION3E43Q.js +197 -0
- package/dist/cli-bundle/chunks/{chunk-73UGEBRS.js → chunk-JOKATURE.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-RIS565OA.js → chunk-TPXZIBIV.js} +5 -5
- package/dist/cli-bundle/chunks/chunk-YM2YAMF7.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-EYCXHZAG.js → register-list-query-Q7KII4G5.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-4WBRPXLV.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-KGDNRMCL.js → register-operations-SSENDH5B.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-NVXBOD5I.js → register-setup-DOSFBGKE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TZATVC4G.js → chunk-267MUUS6.js} +11 -11
- package/dist/cli-bundle/focused-chunks/chunk-2NNFLLNG.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HAACPSUW.js → chunk-2QSAKMIH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6ROKKT4X.js → chunk-ATEY76SX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-BUCG4ZI2.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SSNDYZTM.js → chunk-CYFK5UPB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EHXIKD6K.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-J4UFYHOD.js → chunk-KGEXTMPG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KP2VQQVQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MHPIL773.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-POEEAD2V.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-T46KLOIB.js → chunk-SALH6B6K.js} +47 -47
- package/dist/cli-bundle/focused-chunks/{chunk-CODV5LUT.js → chunk-SYZENPIT.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-4JPEBFFC.js → chunk-XKAMP5OU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NJ5RLEFD.js → chunk-XPIC53VA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-C7JUBRFP.js → chunk-ZQPGZZWQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZT2DJS27.js +155 -0
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +31 -31
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +32 -32
- 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 +4 -2
- package/dist/core/extensions/loader.js +10 -6
- package/dist/core/extensions/manifest-schema.d.ts +20 -0
- package/dist/core/extensions/manifest-schema.js +52 -0
- package/dist/core/history/replay.js +32 -14
- package/dist/core/schema/fields-file.d.ts +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/runtime-field-values.js +115 -9
- package/dist/core/schema/runtime-schema.d.ts +3 -1
- package/dist/core/schema/runtime-schema.js +124 -3
- package/dist/core/shared/errors.d.ts +10 -0
- package/dist/core/shared/errors.js +2 -2
- package/dist/core/shared/time.d.ts +2 -0
- package/dist/core/shared/time.js +27 -2
- package/dist/sdk/agent/refusal-reachability.d.ts +46 -6
- package/dist/sdk/agent/refusal-reachability.js +350 -8
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +5 -4
- package/dist/sdk/compose.d.ts +6 -2
- package/dist/sdk/compose.js +33 -3
- package/dist/sdk/context-intent-contracts.d.ts +8 -4
- package/dist/sdk/context-intent-contracts.js +76 -31
- package/dist/sdk/dependency-flag-validation.d.ts +9 -2
- package/dist/sdk/dependency-flag-validation.js +101 -35
- package/dist/sdk/environment/host-environment-errors.js +25 -7
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +26 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +14 -2
- package/dist/sdk/governance/assurance-action.d.ts +3 -7
- package/dist/sdk/governance/assurance-action.js +97 -2
- package/dist/sdk/governance/boundary-fixtures.d.ts +86 -0
- package/dist/sdk/governance/boundary-fixtures.js +201 -0
- package/dist/sdk/governance/defect-recurrence-signals.d.ts +10 -0
- package/dist/sdk/governance/defect-recurrence-signals.js +25 -0
- package/dist/sdk/governance/defect-recurrence.d.ts +242 -0
- package/dist/sdk/governance/defect-recurrence.js +523 -0
- package/dist/sdk/governance.d.ts +2 -0
- package/dist/sdk/governance.js +4 -2
- package/dist/sdk/graph/governance.js +3 -2
- package/dist/sdk/guide-topics.js +191 -2
- package/dist/sdk/index.d.ts +3 -0
- package/dist/sdk/index.js +4 -2
- package/dist/sdk/lifecycle/create.js +4 -2
- package/dist/sdk/lifecycle/update-many.js +15 -2
- package/dist/sdk/lifecycle/update.js +5 -2
- package/dist/sdk/linked-artifacts.js +63 -14
- package/dist/sdk/query/get.d.ts +2 -0
- package/dist/sdk/query/get.js +32 -7
- package/dist/sdk/relationship-analytics.js +90 -14
- package/dist/sdk/relationship-kinds/contract.d.ts +4 -0
- package/dist/sdk/relationship-kinds/contract.js +3 -2
- package/dist/sdk/relationships.d.ts +1 -1
- package/dist/sdk/relationships.js +11 -2
- package/dist/sdk/schema.d.ts +1 -0
- package/dist/sdk/schema.js +2 -2
- package/dist/sdk/test/execution.d.ts +6 -2
- package/dist/sdk/test/execution.js +39 -13
- package/dist/types.d.ts +29 -2
- package/dist/types.js +4 -2
- package/docs/CONFIGURATION.md +58 -1
- package/docs/CONTEXT_INTEGRITY_CONTRACTS.md +58 -0
- package/docs/DEFECT_RECURRENCE.md +134 -0
- package/docs/DEPENDENCY_KIND_CONTRACT.md +12 -2
- package/docs/README.md +2 -0
- package/docs/RELATIONSHIP_GRAPH.md +16 -2
- package/docs/SDK.md +38 -5
- package/docs/SDK_RUNTIME_BOUNDARIES.md +9 -1
- package/docs/TESTING.md +18 -1
- package/docs/TRUSTWORTHY_CONTEXT_EVIDENCE.md +1 -1
- package/marketplace.json +2 -2
- package/package.json +6 -4
- 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-claude/skills/pm-audit/SKILL.md +26 -0
- package/plugins/pm-claude/skills/pm-developer/SKILL.md +26 -0
- package/plugins/pm-claude/skills/pm-planner/SKILL.md +26 -0
- package/plugins/pm-claude/skills/pm-release/SKILL.md +26 -0
- package/plugins/pm-claude/skills/pm-workflow/SKILL.md +26 -0
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/skills/pm-auditor/SKILL.md +26 -0
- package/plugins/pm-codex/skills/pm-native/SKILL.md +26 -0
- package/plugins/pm-codex/skills/pm-release/SKILL.md +26 -0
- package/sdk/public-surface.json +588 -20
- package/dist/cli-bundle/chunks/chunk-47OQEOQB.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HCIYWD6M.js +0 -35
- package/dist/cli-bundle/chunks/chunk-IC5W2T34.js +0 -2
- package/dist/cli-bundle/chunks/chunk-PANOOBIS.js +0 -13
- package/dist/cli-bundle/chunks/chunk-TK6N7HGM.js +0 -8
- package/dist/cli-bundle/chunks/chunk-TOFG2URD.js +0 -197
- package/dist/cli-bundle/chunks/register-mutation-7YVIG54J.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-5NMFSX26.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-725JSCMP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-DQ6SMTBF.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-JX5Z344Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-L4RDYBIQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QYZERYR5.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-WY3WRPVN.js +0 -2
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
import Ri 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]="294f3a0c-e74d-5963-b966-8a4443855ce3")}catch{}})();var mn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],ga=2,ha=Object.freeze({migration:"schema",validation:"schema"}),YA=Object.freeze({version:ga,capabilities:[...mn],legacy_aliases:{...ha}}),To=["off","warn","enforce"],So=["off","warn","enforce"],Ao=["none","restricted","strict"];var xo=["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"],Jn=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function Qn(){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]="36b908f0-ea19-5adc-8ccd-320ad3c3b1fe")}catch{}})();var Co=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"]}]),Io=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),jt=".agents/pm",Zn="settings.json";var Op=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],Rp=["decisions","events","reminders","milestones","meetings","plans"],QA=[...Op,...Rp],we={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},Np=["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"],Ae=["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",...Np,"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"],Oo={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}},Ro=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],yt={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 ya(e){return e?[...e]:void 0}var Z={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"},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:[...Ro],lifecycle_closure_like_blocked_reason_patterns:[...yt.blocked_reason],lifecycle_closure_like_resolution_patterns:[...yt.resolution],lifecycle_closure_like_actual_result_patterns:[...yt.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...Oo.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!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:Co.map(e=>({...e,aliases:ya(e.aliases),roles:ya(e.roles)})),fields:[],workflow:{...Io},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:Qn()},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:""}}},No={metadata:{},body:""},g={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},ZA=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 Am}from"@toon-format/toon";import{isDeepStrictEqual as Ba}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]="8b39bc01-0325-5dc6-8492-585c98608076")}catch{}})();var Do=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],ba=Do,Ut=["draft","open","in_progress","blocked","closed","canceled"],er=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],zt=["string","number","boolean","string_array","array","object"],tr=["create","update","update_many","list","search","calendar","context"],nr=["allow","warn","reject"];var Lo=["project","global"];var rr=["low","medium","high","critical"],or=["low","medium","high"];var wa=["minimal","default","strict","custom"];var ir=["daily","weekly","monthly","yearly"],_n=["mon","tue","wed","thu","fri","sat","sun"];function Po(e){return _n.indexOf(e)}var va=["draft","research","review","approved","executing","paused","completed","superseded"],sr=["pending","in_progress","completed","blocked","skipped","superseded"],Ea=["codex","claude-code","cursor","generic"],ka=["related","blocks","blocked_by","depends_on","discovered_from","implements","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]="bf08255e-7ef4-5929-8431-2df83d98d0ba")}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 Ta from"node:path";import*as Y from"node:fs/promises";import ar from"node:path";import Dp 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 Lp=[10,25,50,100];async function wt(e){await Y.mkdir(e,{recursive:!0})}async function N(e){try{return await Y.access(e),!0}catch{return!1}}function Mo(e){return X(e)||bt(e,"ENOTDIR")}function X(e){return bt(e,"ENOENT")}async function V(e){try{return await Y.readFile(e,"utf8")}catch(t){if(Mo(t))return null;throw t}}async function L(e,t){let n=ar.dirname(e);await wt(n);let r=ar.join(n,`.${ar.basename(e)}.${process.pid}.${Date.now()}.${Dp.randomBytes(4).toString("hex")}.tmp`);await Y.writeFile(r,t,"utf8");try{await Y.rename(r,e)}catch(o){if(process.platform==="win32"&&(bt(o,"EPERM")||bt(o,"EBUSY"))){let i=o;for(let s of Lp){await new Promise(a=>setTimeout(a,s));try{await Y.rename(r,e);return}catch(a){if(i=a,!bt(a,"EPERM")&&!bt(a,"EBUSY"))break}}try{await Y.unlink(r)}catch{}throw i}if(bt(o,"EXDEV")){try{await Y.copyFile(r,e)}finally{try{await Y.unlink(r)}catch{}}return}try{await Y.unlink(r)}catch{}throw o}}async function qt(e,t){let n=ar.dirname(e);await wt(n);let r=await Y.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
-
`,"utf8")}finally{await r.close()}}function bt(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]="
|
|
3
|
-
`}function Jp(){return{definitions:[]}}function Qp(){return{statuses:jo}}function Zp(){return{fields:[]}}function em(){return{workflow:xa}}function tm(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function nm(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 rm(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 om(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 im(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 sm(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 me(e,t,n){let r=t?.trim()||n;return Ta.isAbsolute(r)?r:Ta.join(e,r)}async function Ra(e,t){let n=Je(t),r=[{path:me(e,n.files.types,ae.types),seed:Jp()},{path:me(e,n.files.statuses,ae.statuses),seed:Qp()},{path:me(e,n.files.fields,ae.fields),seed:Zp()},{path:me(e,n.files.workflows,ae.workflows),seed:em()}],o=[];for(let i of r)await N(i.path)||(await L(i.path,Xp(i.seed)),o.push(i.path));return{created_paths:o}}async function Na(e,t){let n=Je(t),r=[],o=me(e,n.files.types,ae.types),i=me(e,n.files.statuses,ae.statuses),s=me(e,n.files.fields,ae.fields),a=me(e,n.files.workflows,ae.workflows),c,l,d,u,f,m=async(I,A)=>{let O=await V(I);if(O!==null)return tm(O,A,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=nm(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let h=await m(i,"runtime_schema_statuses_invalid_json");h!==void 0&&(l=rm(h),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await m(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=om(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=im(v),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=sm(v)),{schema:Je({...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 Fo(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=>xe(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 hn(e){let t=Je(e),n=t.statuses.map((h,b)=>$o(h,b)).filter(h=>h!==null),r=new Map,o=new Map;for(let h of n){o.set(h.id,h),r.set(h.id,h.id),r.set(h.id.replaceAll("_","-"),h.id),r.set(h.id.replaceAll("_"," "),h.id);for(let b of h.aliases)r.set(b,h.id),r.set(b.replaceAll("_","-"),h.id),r.set(b.replaceAll("_"," "),h.id)}let i=new Set,s=new Set,a=new Set,c=new Set,l=new Set,d=new Set;for(let h of n){let b=new Set(h.roles);(b.has("terminal")||b.has("terminal_done")||b.has("terminal_canceled"))&&i.add(h.id),b.has("terminal_done")&&s.add(h.id),b.has("terminal_canceled")&&a.add(h.id),b.has("active")&&c.add(h.id),b.has("blocked")&&l.add(h.id),b.has("draft")&&d.add(h.id)}let u=t.workflow,f=xe(u.open_status)??Fo(n,"default_open",["open","in_progress",Ut[0]]),m=xe(u.close_status)??Fo(n,"default_close",["closed","done","complete"]),_=xe(u.canceled_status)??Fo(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 Uo(e,t){let n=Pe(e);if(n)return t.alias_to_id.get(n)}function zo(e){let t=Je(e),n=new Map,r=t.fields.map(c=>Oa(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(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9bef4fe4-11a8-51ae-a42a-a93cc9c57384")}catch{}})();function Pa(e){return Array.isArray(e)?e.flatMap(t=>Pa(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 Da(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`,g.USAGE)}function La(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`,g.USAGE);return r}function am(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}`,g.USAGE)}function lr(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:am(i,r,e.type)}if(e.repeatable||e.type==="string_array"){let i=Pa(t);return e.type==="number"?i.map(s=>La(s,r)):e.type==="boolean"?i.map(s=>Da(s,r)):i}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?La(o,r):e.type==="boolean"?Da(o,r):typeof o=="string"?o:String(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]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var Gt=1,dr=1;function Ma(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=Gt?t:Gt}function Fa(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=Gt))return e}function cm(e,t=dr){return e<t?"outdated":e>t?"ahead":"current"}function $a(e,t=dr){let n=[],r=[];for(let o of e){let i=cm(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 lm={"in-progress":"in_progress",cancelled:"canceled"};function vt(e,t){if(t){let o=Uo(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=lm[n]??n;if(Ut.includes(r))return r}import{decode as dm}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 qo(e){return{value:dm(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 um=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function fm(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(um);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Ce(e){return fm(e)[0]}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 mm(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function _m(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=ur(o))}return n}function ur(e){let t=mm(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>ur(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return ur(r)}return _m(e)}function P(e){return JSON.stringify(ur(e))}function ja(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 gm(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function hm(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function ym(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(!ja(o,n,r,ve))return!1;return!0}function bm(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(!ja([o,i],n,r,([a,c],[l,d])=>ve(a,l)&&ve(c,d)))return!1;return!0}function wm(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)=>ve(n,t[r]))}function vm(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]||!ve(e[i],t[i]))return!1}return!0}var Em=[gm,hm,ym,bm,wm];function ve(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 Em){let r=n(e,t);if(r!==void 0)return r}return vm(e,t)}function qe(e){return pm.createHash("sha256").update(e,"utf8").digest("hex")}function Qe(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}import{AsyncLocalStorage as km}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]="cc84ae55-6dc4-57d4-b7de-c43ae1fb4603")}catch{}})();var Tm=new km;function Ua(){let e=Tm.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]="6be1497f-a0d5-518b-bf6a-e549b18fad8a")}catch{}})();function F(){return Ua()??new Date().toISOString()}function Ze(e){return Number.isFinite(Date.parse(e))}var Sm=1e4,fr=new Map;function za(e){let t=fr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return fr.size>=Sm&&Bt(fr),fr.set(e,n),n}function ce(e,t){let n=za(e),r=za(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(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]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function yn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function se(e){return yn(e)??void 0}function Be(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function qa(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]="eaf0e260-a864-57cf-b23b-aac4f9151d8e")}catch{}})();var xm=new Set(["schema","tracker","auto"]),Cm=new Set(["passed","failed","stopped","canceled"]),Im=new Set(sr);function Wt(e){return e.replaceAll("\\","/")}function Ha(e){for(let t of e)if(t!==0)return t;return 0}function pr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Wa=["id","title","description","created_at","updated_at"],Om=new Set(Ae);function Ka(e){if(e?.schema)return{statusRegistry:hn(e.schema),fieldRegistry:zo(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Rm(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function et(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new y(`Invalid item metadata: ${e}`,g.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function vn(e,t){throw new y(t,g.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Ya(e){let t=new Set(Om);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function S(e,t){e||et(t)}function En(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&et(t),e}function Bo(e,t){let n=e[t];S(typeof n=="string",`${t} must be a string`),S(Ze(n),`${t} must be a valid ISO timestamp`)}function Ga(e,t,n){let r=e[t];r!==void 0&&S(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Ho(e,t,n){let r=e[t];r!==void 0&&(S(typeof r=="string",`${n} must be a string`),S(Ze(r),`${n} must be a valid ISO timestamp`))}function Nm(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){S(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();S(_n.includes(n),`event.recurrence.by_weekday entries must be one of: ${_n.join(", ")}`)}}}function Dm(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)S(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Lm(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)S(typeof t=="string","event.recurrence.exdates entries must be strings"),S(Ze(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Pm(e){let t=En(e,"event.recurrence must be an object");S(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();S(ir.includes(n),`event.recurrence.freq must be one of: ${ir.join(", ")}`),Ga(t,"interval","event.recurrence.interval"),Ga(t,"count","event.recurrence.count"),Ho(t,"until","event.recurrence.until"),Nm(t.by_weekday),Dm(t.by_month_day),Lm(t.exdates)}function Mm(e){for(let r of Wa)S(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;S(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&S(typeof n=="number"&&Number.isInteger(n)&&n>=Gt,`pm_format_version must be an integer >= ${Gt}`),t}function Fm(e,t){let n=e.status;S(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=vt(n,r),i=r?r.definitions.map(s=>s.id):[...Ut];S(o!==void 0,`status must be one of: ${i.join(", ")}`)}function $m(e){let t=e.priority;S(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;S(Array.isArray(n),"tags must be an array");for(let r of n)S(typeof r=="string","tags entries must be strings")}function jm(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){S(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"||or.includes(n);S(r,`confidence string value must be one of: ${[...or,"med"].join(", ")}`);return}S(!1,"confidence must be a number or string")}}function Um(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&et("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||rr.includes(n);S(r,`severity value must be one of: ${[...rr,"med"].join(", ")}`)}function zm(e){e.regression!==void 0&&typeof e.regression!="boolean"&&et("regression must be a boolean")}function qm(e){let t=e.reminders;if(t!==void 0){S(Array.isArray(t),"reminders must be an array");for(let n of t){let r=En(n,"reminders entries must be objects");S(typeof r.at=="string","reminder.at must be a string"),S(Ze(r.at),"reminder.at must be a valid ISO timestamp"),S(typeof r.text=="string","reminder.text must be a string"),S(r.text.trim().length>0,"reminder.text must not be empty")}}}function Bm(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(S(typeof e[t]=="string",`event.${t} must be a string`),S(e[t].trim().length>0,`event.${t} must not be empty`))}function Gm(e){e.recurrence!==void 0&&(Pm(e.recurrence),e.recurrence.until!==void 0&&S(ce(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Vm(e){let t=En(e,"events entries must be objects");S(typeof t.start_at=="string","event.start_at must be a string"),S(Ze(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(S(typeof t.end_at=="string","event.end_at must be a string"),S(Ze(t.end_at),"event.end_at must be a valid ISO timestamp"),S(ce(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Bm(t),t.all_day!==void 0&&S(typeof t.all_day=="boolean","event.all_day must be a boolean"),Gm(t)}function Hm(e){let t=e.events;if(t!==void 0){S(Array.isArray(t),"events must be an array");for(let n of t)Vm(n)}}function Wm(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&S(typeof n=="string",`${t} must be a string`)}}function Km(e){let t=e.type_options;if(t===void 0)return;let n=En(t,"type_options must be an object");for(let[r,o]of Object.entries(n))S(r.trim().length>0,"type_options keys must be non-empty"),S(typeof o=="string","type_options values must be strings"),S(o.trim().length>0,"type_options values must be non-empty strings")}function Ym(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Rm(r,t)&&et(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=lr(r,o,`metadata field "${r.metadata_key}"`)}catch(i){et(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Xm(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Ya(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?et(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Wo(e,t){let n=En(e,"item metadata must be an object"),r=Mm(n);Fm(n,t),$m(n),jm(n),Um(n),zm(n),Bo(n,"created_at"),Bo(n,"updated_at"),n.deadline!==void 0&&Bo(n,"deadline"),qm(n),Hm(n),Ho(n,"closed_at","closed_at"),Ho(n,"completed_at","completed_at"),Wm(n),Km(n),Ym(n,r,t),Xm(n,t)}function Jm(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=ce(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 Go(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=ce(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 Qm(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=ce(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function Zm(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!ir.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>_n.includes(s)))).sort((s,a)=>Po(s)-Po(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=>Ze(s)))).sort((s,a)=>ce(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 e_(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(t_).sort(n_)}function t_(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:Zm(e.recurrence)};return pr(t),t}function n_(e,t){return Ha([ce(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 r_(e){if(!(!e||e.length===0))return e.map(t=>({path:Wt(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function o_(e){if(!e||e.length===0)return;let t=e.map(a_).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)=>Ha([ce(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 Vt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function i_(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Vo(e){return typeof e=="string"?e:""}function s_(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 a_(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=Cm.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Vo(e.started_at),finished_at:Vo(e.finished_at),recorded_at:Vo(e.recorded_at),attempt:i_(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:Vt(e.passed)??0,failed:Vt(e.failed)??0,skipped:Vt(e.skipped)??0,items:Vt(e.items),linked_tests:Vt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:s_(e.measurements)};return pr(o),o}function c_(e){if(!(!Array.isArray(e)||e.length===0))return e.map(u_)}function bn(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 Xa(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Yo(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Va(e){if(!Xa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Yo(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function l_(e){if(!Xa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Yo(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function d_(e){let t=e?.trim().toLowerCase();if(!(!t||!xm.has(t)))return t}function u_(e){let t={command:e.command?.trim()||void 0,path:e.path?Wt(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:d_(e.pm_context_mode),env_set:Va(e.env_set),env_clear:bn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:bn(e.assert_stdout_contains),assert_stdout_regex:bn(e.assert_stdout_regex),assert_stderr_contains:bn(e.assert_stderr_contains),assert_stderr_regex:bn(e.assert_stderr_regex),assert_stdout_min_lines:Vt(e.assert_stdout_min_lines),assert_json_field_equals:Va(e.assert_json_field_equals),assert_json_field_gte:l_(e.assert_json_field_gte),note:e.note?.trim()||void 0};return pr(t),t}function f_(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Wt(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 T(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function p_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.id),i=T(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=T(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 m_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.path);if(!o)continue;let i={path:Wt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=T(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function __(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.command),i=T(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Wt(i));let a=T(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function g_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.path);if(!o)continue;let i={path:Wt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=T(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function h_(e){if(e===null||typeof e!="object")return;let t=e,n=T(t.id),r=T(t.title),o=T(t.status),i=o&&Im.has(o)?o:void 0,s=qa(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 y_(l,t),l}function y_(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=T(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",p_],["files","files",m_],["tests","tests",__],["docs","docs",g_]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function b_(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=h_(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function w_(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=T(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=T(r.rationale);c&&(a.rationale=c);let l=T(r.evidence);l&&(a.evidence=l);let d=T(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function v_(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=T(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=T(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function E_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.text);if(!o)continue;let i={text:o},s=T(r.command);s&&(i.command=s);let a=T(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function k_(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 Ht(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 Pi 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]="294f3a0c-e74d-5963-b966-8a4443855ce3")}catch{}})();var _n=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],Ea=2,va=Object.freeze({migration:"schema",validation:"schema"}),gx=Object.freeze({version:Ea,capabilities:[..._n],legacy_aliases:{...va}}),Co=["off","warn","enforce"],Io=["off","warn","enforce"],Oo=["none","restricted","strict"];var Ro=["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"],Qn=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function Zn(){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]="36b908f0-ea19-5adc-8ccd-320ad3c3b1fe")}catch{}})();var No=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"]}]),Do=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Ut=".agents/pm",er="settings.json";var Mp=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],Fp=["decisions","events","reminders","milestones","meetings","plans"],bx=[...Mp,...Fp],we={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},$p=["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"],Ae=["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",...$p,"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"],Lo={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}},Po=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],yt={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 ka(e){return e?[...e]:void 0}var Z={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"},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:[...Po],lifecycle_closure_like_blocked_reason_patterns:[...yt.blocked_reason],lifecycle_closure_like_resolution_patterns:[...yt.resolution],lifecycle_closure_like_actual_result_patterns:[...yt.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...Lo.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!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:No.map(e=>({...e,aliases:ka(e.aliases),roles:ka(e.roles)})),fields:[],workflow:{...Do},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:Zn()},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:""}}},Mo={metadata:{},body:""},h={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},wx=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 qm}from"@toon-format/toon";import{isDeepStrictEqual as Xa}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]="4e2028b3-6718-509a-b687-d1df58962387")}catch{}})();var Fo=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],Ta=Fo,zt=["draft","open","in_progress","blocked","closed","canceled"],tr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],qt=["string","number","boolean","string_array","array","object"],nr=["create","update","update_many","list","search","calendar","context"],rr=["allow","warn","reject"];var $o=["project","global"];var or=["low","medium","high","critical"],ir=["low","medium","high"];var Sa=["minimal","default","strict","custom"];var sr=["daily","weekly","monthly","yearly"],gn=["mon","tue","wed","thu","fri","sat","sun"];function jo(e){return gn.indexOf(e)}var Aa=["draft","research","review","approved","executing","paused","completed","superseded"],ar=["pending","in_progress","completed","blocked","skipped","superseded"],xa=["codex","claude-code","cursor","generic"],Ca=["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]="c863f07f-428b-5b7f-a5f7-23e7f5fa749a")}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 jp 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 Up(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 zp(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=cr(o))}return n}function cr(e){let t=Up(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>cr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return cr(r)}return zp(e)}function R(e){return JSON.stringify(cr(e))}function Ia(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 qp(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function Bp(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function Gp(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(!Ia(o,n,r,Ee))return!1;return!0}function Vp(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(!Ia([o,i],n,r,([a,c],[l,d])=>Ee(a,l)&&Ee(c,d)))return!1;return!0}function Hp(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)=>Ee(n,t[r]))}function Wp(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]||!Ee(e[i],t[i]))return!1}return!0}var Kp=[qp,Bp,Gp,Vp,Hp];function Ee(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 Kp){let r=n(e,t);if(r!==void 0)return r}return Wp(e,t)}function qe(e){return jp.createHash("sha256").update(e,"utf8").digest("hex")}function Je(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 Bt(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 Yp}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]="cc84ae55-6dc4-57d4-b7de-c43ae1fb4603")}catch{}})();var Xp=new Yp;function Oa(){let e=Xp.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 Jp=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function F(){return Oa()??new Date().toISOString()}function Qe(e){return Number.isFinite(Date.parse(e))}function Na(e){let t=Jp.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<=Zp(d,u-1)&&p<=23&&_<=59&&g<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var Qp=1e4,lr=new Map;function Ra(e){let t=lr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return lr.size>=Qp&&Bt(lr),lr.set(e,n),n}function ae(e,t){let n=Ra(e),r=Ra(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function Zp(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import Da from"node:path";import*as Y from"node:fs/promises";import dr from"node:path";import em 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 tm=[10,25,50,100];async function wt(e){await Y.mkdir(e,{recursive:!0})}async function D(e){try{return await Y.access(e),!0}catch{return!1}}function Uo(e){return X(e)||bt(e,"ENOTDIR")}function X(e){return bt(e,"ENOENT")}async function V(e){try{return await Y.readFile(e,"utf8")}catch(t){if(Uo(t))return null;throw t}}async function P(e,t){let n=dr.dirname(e);await wt(n);let r=dr.join(n,`.${dr.basename(e)}.${process.pid}.${Date.now()}.${em.randomBytes(4).toString("hex")}.tmp`);await Y.writeFile(r,t,"utf8");try{await Y.rename(r,e)}catch(o){if(process.platform==="win32"&&(bt(o,"EPERM")||bt(o,"EBUSY"))){let i=o;for(let s of tm){await new Promise(a=>setTimeout(a,s));try{await Y.rename(r,e);return}catch(a){if(i=a,!bt(a,"EPERM")&&!bt(a,"EBUSY"))break}}try{await Y.unlink(r)}catch{}throw i}if(bt(o,"EXDEV")){try{await Y.copyFile(r,e)}finally{try{await Y.unlink(r)}catch{}}return}try{await Y.unlink(r)}catch{}throw o}}async function Gt(e,t){let n=dr.dirname(e);await wt(n);let r=await Y.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
+
`,"utf8")}finally{await r.close()}}function bt(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 nm=2e3,ur=new Map;function Pe(e){if(typeof e!="string")return"";let t=ur.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return ur.size>=nm&&Bt(ur),ur.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 ce=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Ma=Do,Bo=No,rm=["create","update"],om=new Set(tr),im=new Set(qt),sm=new Set(nr),am=new Set(rr),cm=new Set(["string","number","boolean","array","object"]),lm=16;function Fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var dm=[e=>e.type===void 0||typeof e.type=="string"&&cm.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||Fa(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 fr(e,t=0,n=new Set){if(!Fa(e)||t>lm||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(!dm.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,C])=>[v,fr(C,t+1,n)])),g=c===void 0?void 0:fr(c,t+1,n),b=s===void 0?void 0:s.map(v=>fr(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[g],...b??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:d,min_items:u,format:f,properties:_,required:l===void 0?void 0:[...new Set(l)],additional_properties:p,items:g,one_of:b}).filter(([,v])=>v!==void 0))}function hn(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 xe(e){if(typeof e!="string"||e.length===0)return;let t=Pe(e);return t.length>0?t:void 0}function um(e){return e.startsWith("--")?e.slice(2):e}function La(e){return typeof e=="string"?um(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function $a(e){return e.replaceAll("_","-")}function qo(e,t){let n=xe(e.id);if(!n)return null;let r=[...new Set(hn(e.aliases).map(Pe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=hn(e.roles).filter(a=>om.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 fm(e){return{draft_status:xe(e?.draft_status),open_status:xe(e?.open_status),in_progress_status:xe(e?.in_progress_status),blocked_status:xe(e?.blocked_status),close_status:xe(e?.close_status),canceled_status:xe(e?.canceled_status)}}function ja(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Pe(t[0]),r=Pe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function pm(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)ja(n,r);return{typeKey:t.toLowerCase(),record:n}}function mm(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=pm(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)ja(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 Ua(e){let t=Pe(e.key??"");if(!t)return null;let n=Pe(e.metadata_key??e.front_matter_key??t),r=La(e.cli_flag??$a(t));if(!r)return null;let o=hn(e.cli_aliases).map(u=>La(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=im.has(i)?i:"string",a=(()=>{let u=hn(e.commands).filter(f=>sm.has(f));return u.length>0?u:[...rm]})(),c=e.description?.trim(),l=hn(e.required_types),d=e.value_schema===void 0?void 0:fr(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 _m(e){let t=new Map;for(let[r,o]of e.entries()){let i=qo(o,r);i&&t.set(i.id,i)}let n=Pa([...t.values()]);return n.length>0?n:Pa(Bo.map((r,o)=>qo(r,o)).filter(r=>r!==null))}function Pa(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function gm(e){let t=new Map;for(let n of e??[]){let r=Ua(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function hm(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 ym(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==$a(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 bm(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return am.has(t)?t:"allow"}function Ze(e){let t={...ce,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:Bo,r=_m(n),o=gm(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(hm),fields:o.map(ym),workflow:{...Ma,...fm(e?.workflow)},type_workflows:mm(e?.type_workflows),unknown_field_policy:bm(e?.unknown_field_policy)}}function wm(e){return`${JSON.stringify(e,null,2)}
|
|
3
|
+
`}function Em(){return{definitions:[]}}function vm(){return{statuses:Bo}}function km(){return{fields:[]}}function Tm(){return{workflow:Ma}}function Sm(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function Am(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 xm(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 Cm(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 Im(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 Om(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 me(e,t,n){let r=t?.trim()||n;return Da.isAbsolute(r)?r:Da.join(e,r)}async function za(e,t){let n=Ze(t),r=[{path:me(e,n.files.types,ce.types),seed:Em()},{path:me(e,n.files.statuses,ce.statuses),seed:vm()},{path:me(e,n.files.fields,ce.fields),seed:km()},{path:me(e,n.files.workflows,ce.workflows),seed:Tm()}],o=[];for(let i of r)await D(i.path)||(await P(i.path,wm(i.seed)),o.push(i.path));return{created_paths:o}}async function qa(e,t){let n=Ze(t),r=[],o=me(e,n.files.types,ce.types),i=me(e,n.files.statuses,ce.statuses),s=me(e,n.files.fields,ce.fields),a=me(e,n.files.workflows,ce.workflows),c,l,d,u,f,p=async(C,A)=>{let O=await V(C);if(O!==null)return Sm(O,A,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=Am(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let g=await p(i,"runtime_schema_statuses_invalid_json");g!==void 0&&(l=xm(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=Cm(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let E=await p(a,"runtime_schema_workflows_invalid_json");return E!==void 0&&(u=Im(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=Om(E)),{schema:Ze({...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 zo(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=>xe(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 yn(e){let t=Ze(e),n=t.statuses.map((g,b)=>qo(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=xe(u.open_status)??zo(n,"default_open",["open","in_progress",zt[0]]),p=xe(u.close_status)??zo(n,"default_close",["closed","done","complete"]),_=xe(u.canceled_status)??zo(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 Go(e,t){let n=Pe(e);if(n)return t.alias_to_id.get(n)}function Vo(e){let t=Ze(e),n=new Map,r=t.fields.map(c=>Ua(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(){try{var e=typeof window<"u"?window:typeof 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 Rm=16;function Va(e){return Array.isArray(e)?e.flatMap(t=>Va(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 Ba(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 Ga(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 Nm(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 Dm(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 Lm(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!Dm(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"&&!Na(e))return`${n} must be an RFC 3339 date-time`}}function Pm(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 Mm(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>Rm)return`${n} value schema exceeds maximum depth`;let o=Lm(e,t,n);if(o)return o;let i=Pm(e,t,n,r);if(i)return i;let s=Mm(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 Et(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 _r(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:Et(e,Nm(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=Va(t);return e.type==="number"?Et(e,i.map(s=>Ga(s,r)),r):e.type==="boolean"?Et(e,i.map(s=>Ba(s,r)),r):Et(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?Et(e,Ga(o,r),r):e.type==="boolean"?Et(e,Ba(o,r),r):Et(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 Vt=1,gr=1;function Ha(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=Vt?t:Vt}function Wa(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=Vt))return e}function Fm(e,t=gr){return e<t?"outdated":e>t?"ahead":"current"}function Ka(e,t=gr){let n=[],r=[];for(let o of e){let i=Fm(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 $m={"in-progress":"in_progress",cancelled:"canceled"};function vt(e,t){if(t){let o=Go(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=$m[n]??n;if(zt.includes(r))return r}import{decode as jm}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 Ho(e){return{value:jm(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 Um=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function zm(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(Um);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Ce(e){return zm(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 bn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function se(e){return bn(e)??void 0}function Be(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Ya(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]="eaf0e260-a864-57cf-b23b-aac4f9151d8e")}catch{}})();var Bm=new Set(["schema","tracker","auto"]),Gm=new Set(["passed","failed","stopped","canceled"]),Vm=new Set(ar);function Kt(e){return e.replaceAll("\\","/")}function Za(e){for(let t of e)if(t!==0)return t;return 0}function hr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var ec=["id","title","description","created_at","updated_at"],Hm=new Set(Ae);function tc(e){if(e?.schema)return{statusRegistry:yn(e.schema),fieldRegistry:Vo(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Wm(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function et(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 vn(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 nc(e){let t=new Set(Hm);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function S(e,t){e||et(t)}function kn(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&et(t),e}function Wo(e,t){let n=e[t];S(typeof n=="string",`${t} must be a string`),S(Qe(n),`${t} must be a valid ISO timestamp`)}function Ja(e,t,n){let r=e[t];r!==void 0&&S(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Xo(e,t,n){let r=e[t];r!==void 0&&(S(typeof r=="string",`${n} must be a string`),S(Qe(r),`${n} must be a valid ISO timestamp`))}function Km(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){S(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();S(gn.includes(n),`event.recurrence.by_weekday entries must be one of: ${gn.join(", ")}`)}}}function Ym(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)S(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Xm(e){if(e!==void 0){S(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)S(typeof t=="string","event.recurrence.exdates entries must be strings"),S(Qe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Jm(e){let t=kn(e,"event.recurrence must be an object");S(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();S(sr.includes(n),`event.recurrence.freq must be one of: ${sr.join(", ")}`),Ja(t,"interval","event.recurrence.interval"),Ja(t,"count","event.recurrence.count"),Xo(t,"until","event.recurrence.until"),Km(t.by_weekday),Ym(t.by_month_day),Xm(t.exdates)}function Qm(e){for(let r of ec)S(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;S(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&S(typeof n=="number"&&Number.isInteger(n)&&n>=Vt,`pm_format_version must be an integer >= ${Vt}`),t}function Zm(e,t){let n=e.status;S(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=vt(n,r),i=r?r.definitions.map(s=>s.id):[...zt];S(o!==void 0,`status must be one of: ${i.join(", ")}`)}function e_(e){let t=e.priority;S(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;S(Array.isArray(n),"tags must be an array");for(let r of n)S(typeof r=="string","tags entries must be strings")}function t_(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){S(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||ir.includes(n);S(r,`confidence string value must be one of: ${[...ir,"med"].join(", ")}`);return}S(!1,"confidence must be a number or string")}}function n_(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&et("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||or.includes(n);S(r,`severity value must be one of: ${[...or,"med"].join(", ")}`)}function r_(e){e.regression!==void 0&&typeof e.regression!="boolean"&&et("regression must be a boolean")}function o_(e){let t=e.reminders;if(t!==void 0){S(Array.isArray(t),"reminders must be an array");for(let n of t){let r=kn(n,"reminders entries must be objects");S(typeof r.at=="string","reminder.at must be a string"),S(Qe(r.at),"reminder.at must be a valid ISO timestamp"),S(typeof r.text=="string","reminder.text must be a string"),S(r.text.trim().length>0,"reminder.text must not be empty")}}}function i_(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(S(typeof e[t]=="string",`event.${t} must be a string`),S(e[t].trim().length>0,`event.${t} must not be empty`))}function s_(e){e.recurrence!==void 0&&(Jm(e.recurrence),e.recurrence.until!==void 0&&S(ae(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function a_(e){let t=kn(e,"events entries must be objects");S(typeof t.start_at=="string","event.start_at must be a string"),S(Qe(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(S(typeof t.end_at=="string","event.end_at must be a string"),S(Qe(t.end_at),"event.end_at must be a valid ISO timestamp"),S(ae(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),i_(t),t.all_day!==void 0&&S(typeof t.all_day=="boolean","event.all_day must be a boolean"),s_(t)}function c_(e){let t=e.events;if(t!==void 0){S(Array.isArray(t),"events must be an array");for(let n of t)a_(n)}}function l_(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&S(typeof n=="string",`${t} must be a string`)}}function d_(e){let t=e.type_options;if(t===void 0)return;let n=kn(t,"type_options must be an object");for(let[r,o]of Object.entries(n))S(r.trim().length>0,"type_options keys must be non-empty"),S(typeof o=="string","type_options values must be strings"),S(o.trim().length>0,"type_options values must be non-empty strings")}function u_(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Wm(r,t)&&et(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=_r(r,o,`metadata field "${r.metadata_key}"`)}catch(i){et(String(i?.message).replace(/^Invalid\s+/u,""))}}}function f_(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=nc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?et(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Jo(e,t){let n=kn(e,"item metadata must be an object"),r=Qm(n);Zm(n,t),e_(n),t_(n),n_(n),r_(n),Wo(n,"created_at"),Wo(n,"updated_at"),n.deadline!==void 0&&Wo(n,"deadline"),o_(n),c_(n),Xo(n,"closed_at","closed_at"),Xo(n,"completed_at","completed_at"),l_(n),d_(n),u_(n,r,t),f_(n,t)}function p_(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=ae(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 Ko(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=ae(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 m_(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=ae(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function __(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!sr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>gn.includes(s)))).sort((s,a)=>jo(s)-jo(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=>Qe(s)))).sort((s,a)=>ae(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 g_(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(h_).sort(y_)}function h_(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:__(e.recurrence)};return hr(t),t}function y_(e,t){return Za([ae(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 b_(e){if(!(!e||e.length===0))return e.map(t=>({path:Kt(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function w_(e){if(!e||e.length===0)return;let t=e.map(k_).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)=>Za([ae(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 Ht(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function E_(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Yo(e){return typeof e=="string"?e:""}function v_(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 k_(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=Gm.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Yo(e.started_at),finished_at:Yo(e.finished_at),recorded_at:Yo(e.recorded_at),attempt:E_(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:Ht(e.passed)??0,failed:Ht(e.failed)??0,skipped:Ht(e.skipped)??0,items:Ht(e.items),linked_tests:Ht(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:v_(e.measurements)};return hr(o),o}function T_(e){if(!(!Array.isArray(e)||e.length===0))return e.map(x_)}function wn(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 rc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Zo(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Qa(e){if(!rc(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Zo(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function S_(e){if(!rc(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Zo(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function A_(e){let t=e?.trim().toLowerCase();if(!(!t||!Bm.has(t)))return t}function x_(e){let t={command:e.command?.trim()||void 0,path:e.path?Kt(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:A_(e.pm_context_mode),env_set:Qa(e.env_set),env_clear:wn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:wn(e.assert_stdout_contains),assert_stdout_regex:wn(e.assert_stdout_regex),assert_stderr_contains:wn(e.assert_stderr_contains),assert_stderr_regex:wn(e.assert_stderr_regex),assert_stdout_min_lines:Ht(e.assert_stdout_min_lines),assert_json_field_equals:Qa(e.assert_json_field_equals),assert_json_field_gte:S_(e.assert_json_field_gte),note:e.note?.trim()||void 0};return hr(t),t}function C_(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Kt(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 T(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function I_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.id),i=T(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=T(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 O_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.path);if(!o)continue;let i={path:Kt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=T(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function R_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.command),i=T(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Kt(i));let a=T(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function N_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.path);if(!o)continue;let i={path:Kt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=T(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function D_(e){if(e===null||typeof e!="object")return;let t=e,n=T(t.id),r=T(t.title),o=T(t.status),i=o&&Vm.has(o)?o:void 0,s=Ya(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 L_(l,t),l}function L_(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=T(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",I_],["files","files",O_],["tests","tests",R_],["docs","docs",N_]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function P_(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=D_(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function M_(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=T(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=T(r.rationale);c&&(a.rationale=c);let l=T(r.evidence);l&&(a.evidence=l);let d=T(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function F_(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=T(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=T(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function $_(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=T(r.text);if(!o)continue;let i={text:o},s=T(r.command);s&&(i.command=s);let a=T(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function j_(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 Wt(e){let t=0;for(;t<e.length&&e[t]===`
|
|
4
|
+
`;)t+=1;return e.slice(t).trimEnd()}function U_(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(ir.includes(t))return t}function z_(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(or.includes(t))return t}function En(e){return e||void 0}function q_(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Zo(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function B_(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]=_r(r,o,`metadata field "${r.metadata_key}"`))}}function G_(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=nc(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&et(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function Tn(e,t={}){let n=tc(t),r=vt(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:Wa(e.pm_format_version),source_type:T(e.source_type),type_options:j_(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:p_(e.dependencies),comments:Ko(e.comments),notes:Ko(e.notes),learnings:Ko(e.learnings),files:b_(e.files),tests:T_(e.tests),test_runs:w_(e.test_runs),docs:C_(e.docs),deadline:En(e.deadline),reminders:m_(e.reminders),events:g_(e.events),closed_at:En(e.closed_at),completed_at:En(e.completed_at),assignee:T(e.assignee),claim_principal:T(e.claim_principal),source_owner:T(e.source_owner),author:En(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:T(e.definition_of_ready),order:e.order,goal:T(e.goal),objective:T(e.objective),value:T(e.value),impact:T(e.impact),outcome:T(e.outcome),why_now:T(e.why_now),parent:T(e.parent),reviewer:T(e.reviewer),risk:e.risk??void 0,confidence:U_(e.confidence),sprint:T(e.sprint),release:T(e.release),blocked_by:T(e.blocked_by),blocked_reason:T(e.blocked_reason),unblock_note:T(e.unblock_note),reporter:T(e.reporter),severity:z_(e.severity),environment:T(e.environment),repro_steps:T(e.repro_steps),resolution:T(e.resolution),expected_result:T(e.expected_result),actual_result:T(e.actual_result),affected_version:T(e.affected_version),fixed_version:T(e.fixed_version),component:T(e.component),regression:e.regression,customer_impact:T(e.customer_impact),close_reason:En(e.close_reason),plan_mode:T(e.plan_mode),plan_scope:T(e.plan_scope),plan_harness:T(e.plan_harness),plan_resume_context:T(e.plan_resume_context),plan_steps:P_(e.plan_steps),plan_decisions:M_(e.plan_decisions),plan_discoveries:F_(e.plan_discoveries),plan_validation:$_(e.plan_validation)};return q_(i,e),B_(i,n),G_(i,n),hr(i),i}function oc(e){return Je(e,Ae)}function V_(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 H_(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=V_(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 W_(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 Qo(e,t){return Tn(e,{...t,onWarning:void 0})}function K_(e,t,n={}){let r=W_(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=H_(r.content);o||(e.trimStart().startsWith("{")&&vn("json_markdown","JSON front matter is not valid JSON"),vn("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{vn("json_markdown","JSON front matter is not valid JSON")}return Jo(s,t),{metadata:Qo(s,n),body:Wt(i)}}function Y_(e,t,n={}){let r;try{r=Ho(e).value}catch{vn("toon","TOON item document is not valid TOON")}S(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!ec.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&vn("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Jo(o.front_matter,t),S(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Qo(o.front_matter,n),body:Wt(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return S(i===void 0||typeof i=="string","TOON item document body must be a string"),Jo(s,t),{metadata:Qo(s,n),body:Wt(typeof i=="string"?i:"")}}function X_(e,t={}){let n=Tn(e.metadata,t),r=oc(n),o=JSON.stringify(r,null,2),i=Wt(e.body??"");return i?`${o}
|
|
6
6
|
|
|
7
7
|
${i}
|
|
8
8
|
`:`${o}
|
|
9
|
-
`}function
|
|
10
|
-
`}function Me(e,t={}){let n=Ce(e);if(n)throw new y(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Ka(t);return r==="toon"?D_(e,o,t):N_(e,o,t)}function Et(e,t={}){return(t.format??"toon")==="toon"?P_(e,t):L_(e,t)}function _e(e,t={}){return{metadata:kn(e.metadata,t),body:Ht(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 Qc from"fast-json-patch";import{AsyncLocalStorage as Xg}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{}})();import mr from"node:fs";import kt from"node:path";import{fileURLToPath as M_}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 F_="@unbrained/pm-cli";function $_(e){try{return JSON.parse(mr.readFileSync(e,"utf8")).name===F_}catch{return!1}}function j_(e){let t=mr.existsSync(e)&&mr.statSync(e).isDirectory()?kt.resolve(e):kt.dirname(kt.resolve(e));for(;;){let n=kt.join(t,"package.json");if(mr.existsSync(n)&&$_(n))return t;let r=kt.dirname(t);if(r===t)return;t=r}}function Kt(e,t=[]){let n=M_(e),r=j_(n);return r||kt.resolve(kt.dirname(n),...t)}import{readFileSync as sg,readdirSync as bC,statSync as ag}from"node:fs";import H from"node:path";import G_ 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 tt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function U_(e){let t=e.key.trim();if(t.length===0)return null;let n=tt(e.aliases),r=e.description?.trim();return{key:t,values:tt(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 z_=e=>e,Za=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function q_(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 B_(e,t){let n=new Map;for(let r of e??[]){let o=q_(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 Qa(e,t){return t?tt(e):void 0}function Xo(e){let t=e?.trim();return t&&t.length>0?t:void 0}function _r(e,t={}){let n=t.resolvePolicyCommand??z_,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=tt(e.aliases),l=(e.options??[]).map(u=>U_(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=B_(e.command_option_policies,n);return{name:r,description:Xo(e.description),default_status:Xo(e.default_status),folder:Xo(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Qa(e.required_create_fields,o),required_create_repeatables:Qa(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 V_=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],H_=["dep","comment","note","learning","file","test","doc"],Jo=["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"],uC=["title","description","type","status","priority","tags","body",...Jo,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],fC=["title","description","body","status","closeReason","priority","type","tags",...Jo,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],tc={"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"},pC={...tc},mC={...tc},nc=[["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"]],rc=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function oc(e){return Object.fromEntries(e)}var _C=oc([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...nc,["author","--author"],["message","--message"],["dep","--dep"],...rc]),gC=oc([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...nc,...rc,["author","--author"],["message","--message"],["force","--force"]]);function gr(e){let t=W_(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function ic(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=G_.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 W_(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 K_(e){return _r(e,{resolvePolicyCommand:Za})}function Tn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Y_(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:Tn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Tn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function X_(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 J_(e){if(Array.isArray(e.options))return e.options.map(t=>Y_(t)).filter(t=>t!==null)}function Q_(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>X_(t)).filter(t=>t!==null)}function Z_(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:Tn(t,"aliases"),required_create_fields:Tn(t,"required_create_fields"),required_create_repeatables:Tn(t,"required_create_repeatables"),options:J_(t),command_option_policies:Q_(t)}}function eg(e,t){return e.required_create_fields?tt(e.required_create_fields):t?.required_create_fields??[]}function tg(e,t){return e.required_create_repeatables?tt(e.required_create_repeatables):t?.required_create_repeatables??[]}function ng(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function rg(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function og(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=ic(e.folder??t?.folder??gr(n)),s={name:n,folder:i,aliases:tt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:eg(e,t),required_create_repeatables:tg(e,t),options:ng(e,t),command_option_policies:rg(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function ec(e,t){for(let n of e){let r=K_(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,og(r,i))}}function ig(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=Z_(o);i&&t.push(i)}}return t}function oe(e,t=null){let n=new Map;for(let c of ba)n.set(c.toLowerCase(),{name:c,folder:we[c],aliases:[],required_create_fields:[...V_],required_create_repeatables:[...H_],options:[],command_option_policies:[]});ec(e.item_types?.definitions??[],n),ec(ig(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 cg={json_markdown:".md",toon:".toon"},lg={".md":"json_markdown",".toon":"toon"};var Yt=[".md",".toon"];function hr(e){try{return ag(e),!0}catch{return!1}}function dg(e){try{let t=JSON.parse(sg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function ug(e){let t=H.resolve(e);for(;;){let n=H.join(t,jt),r=H.join(n,Zn);if(hr(r))return n;let o=H.join(t,Zn);if(hr(o)&&dg(o))return t;let i=H.dirname(t);if(i===t)return;t=i}}function sc(e){return ug(e)??H.resolve(e,jt)}function te(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=H.resolve(e,r);if(!hr(U(o))){let i=H.join(o,jt);if(hr(U(i)))return i}return o}return sc(e)}function Qo(e){let t=H.resolve(e),n=H.dirname(t);return H.basename(t)==="pm"&&H.basename(n)===".agents"?H.dirname(n):t}function U(e){return H.join(e,Zn)}function fg(e,t,n=we){let r=n[t]??gr(t);return H.join(e,r)}function Xt(e,t,n,r="toon",o=we){return H.join(fg(e,t,o),`${n}${cg[r]}`)}function yr(e){let t=e.replaceAll("\\","/"),n=H.posix.extname(t).toLowerCase();return lg[n]??null}function Fe(e,t){return H.join(e,"history",`${t}.jsonl`)}function ac(e,t){return H.join(e,"locks",`${t}.lock`)}function cc(e){return H.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 TC=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 Tt(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,h=Math.min(f,m,_);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(h=Math.min(h,o[d-2]+1)),s[d]=h,h<l&&(l=h)}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 lc=zt;function Zo(e){let t=e.trim().toLowerCase();return lc.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 St(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function pg(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function dc(e){return e?Ge(e):{}}function uc(e){return e?Ge(e):pg()}function Ge(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]="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]="45d00ef3-870c-5f3f-89c1-6abd54c518fe")}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 ei=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"}]),mg=new Set(ei.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]="49a83ce3-4c55-5b3f-b061-bc21b716d498")}catch{}})();var ti=[{kind:"blocked_by",direction:"directed",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",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",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",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",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",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]="05e01593-acb6-5e28-a5ac-8c8f74359c62")}catch{}})();function br(e){return e.trim().toLowerCase().replaceAll("-","_")}function _g(e){if(e===void 0)return;let t=br(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function ni(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)ni(n,t);return Object.freeze(e)}for(let n of Object.values(e))ni(n,t);return Object.freeze(e)}function gg(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 hg(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 yg(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=br(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 bg(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}`)}function wg(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}`)}var ri=class{#e=new Map;#t=new Map;constructor(t=ti){for(let n of t)this.register(n)}register(t){let n=yg(t);if(bg(t,n),wg(t,n),gg(t,n),hg(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=_g(t.inverse),o=[...new Set((t.aliases??[]).map(br))].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,hierarchy:t.hierarchy??!1,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?ni(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=br(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 Jt(){return new ri}var GC=Jt();(function(){try{var e=typeof window<"u"?window:typeof 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]="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]="ac377139-8ce2-58ad-8005-0ac907a9baed")}catch{}})();var Tg=5e3;async function pc(e,t,n){let r=[];for(let o of e)try{await o.run(Ge(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function Sg(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.`,g.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new y(`Extension mutation guard ${t.name} returned an invalid denial.`,g.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new y(s||`Extension mutation guard ${t.name} denied ${n}.`,g.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function oi(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:Ge(t.before),after:t.after===null?null:Ge(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}.`,g.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},Tg),o.unref?.()})])}catch(i){throw i instanceof y?i:new y(`Extension mutation guard ${n.name} failed before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Sg(r,n,t.operation)}}async function ii(e,t){return pc(e.onWrite,"onWrite",t)}async function si(e,t){return pc(e.onRead,"onRead",t)}function Ag(e){return{handled:!1,result:e.payload,warnings:[]}}function xg(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Cg(e){return{service:e.service,command:e.command?St(e.command):void 0,args:e.args?Ge(e.args):void 0,options:e.options?dc(e.options):void 0,global:e.global?uc(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:Ge(e.payload)}}function Ig(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 Og(e,t){return Ig(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 Rg(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&ve(e,n.payload)}async function ai(e,t){let n=xg(e,t.service);if(n.length===0)return Ag(t);let r=[];for(let o of n)try{let i=Cg(t),s=await Promise.resolve(o.run(i));if(Rg(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Og(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}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]="2b8750c3-7b19-5240-8179-f83830af1b77")}catch{}})();var DO=Object.freeze(Qn());(function(){try{var e=typeof window<"u"?window:typeof 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 wr=null;var Jg=null;var Qg=null,Zg=null;var eh=[],th=new Xg;function nt(){return th.getStore()}var nh=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function B(){let e=nt();return e?e.registrations:Qg}function ci(e){if(!e)return;let t=nt();t?t.affectedItems.push(e):eh.push(e)}function vr(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"||nh.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function ge(e){let t=nt(),n=t?t.hooks:wr;return n?ii(n,e):[]}async function li(e){let t=nt(),n=t?t.hooks:wr;n&&await oi(n,e)}async function Ie(e){let t=nt(),n=t?t.hooks:wr;return n?si(n,e):[]}function Er(){let e=nt();return((e?e.hooks:wr)?.onRead?.length??0)>0}function rh(e,t){let n=nt(),r=n?n.commandContext:Zg;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 $e(e,t){let n=nt(),r=n?n.services:Jg;return r?ai(r,rh(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as _i}from"node:async_hooks";import{createHash as fh}from"node:crypto";import Sr from"node:fs";import ph from"node:os";import bc from"node:path";import{AsyncLocalStorage as oh}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 ih=new oh,hc=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function kr(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Sn(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=kr(n.id,128),o=kr(n.parent_id,128);if(r===void 0||!hc.test(r)||o!==void 0&&!hc.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=kr(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function di(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=kr(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function sh(e,t,n){let r=ih.getStore(),o=di({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Sn(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={...di(r?.provenance),...o,...di(e?.provenance)},a=Sn(e?.episode,!1)??Sn(n,!1)??i??Sn(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 Tr(e,t){return sh(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as ui,promises as oR,readFileSync as ah}from"node:fs";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]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var ch="session.json";function fi(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function lh(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=fi(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=>fi(c,128)),a=t.focused_item_id===void 0||fi(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function dh(e){return Ve.join(cc(e),ch)}function uh(e,t){let n=t.PM_PATH?.trim();if(n){let o=Ve.resolve(e,n);if(ui(Ve.join(o,"settings.json")))return o;let i=Ve.join(o,".agents","pm");if(ui(Ve.join(i,"settings.json")))return i}let r=Ve.resolve(e);for(let o=0;o<32;o+=1){let i=Ve.join(r,".agents","pm");if(ui(Ve.join(i,"settings.json")))return i;let s=Ve.dirname(r);if(s===r)break;r=s}}function yc(e){if(!e.key)return;let t=uh(e.cwd,e.env);if(t)try{let n=JSON.parse(ah(dh(t),"utf8"));return lh(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]="e0ab2d6f-0925-540d-8d24-a7f0687b4bf0")}catch{}})();var gi=["model","effort","role","topic","version"],xr=new _i,mh=new _i,hi=new _i,_h=[{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:{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:[]}],gh=new Map,pi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ee(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function At(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function wc(e){let t=e.harness.trim().toLowerCase();if(!pi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:At(e.environment_keys),model_environment_keys:At(e.model_environment_keys),session_environment_keys:At(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),At(r)]).filter(([n])=>pi.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"&&pi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"))),provenance_unavailable_dimensions:At(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:At(e.argv_markers).map(n=>n.toLowerCase()),client_names:At(e.client_names).map(n=>n.toLowerCase())}}var hh=_h.map(wc);function Ar(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function vc(e=[]){let t=[...hh,...[...gh.values()].map(r=>r.descriptor),...hi.getStore()?.descriptors??[],...e.map(wc)],n=new Set;for(let r of t){if(n.has(r.harness))throw new Error(`Harness signal descriptor collision for "${r.harness}"`);n.add(r.harness)}return t}function yi(e,t){for(let n of t??[]){let r=ee(e[n]);if(r)return r.slice(0,256)}}function yh(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 Ec(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 ee(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return ee(i.slice(s.length+1))?.slice(0,256)}}var bh=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function xt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return bh.has(n)?n:void 0}function mi(e,t){return ee(e?.[t])?.slice(0,256)}var wh=1048576;function vh(e,t){if(e.length===0||e.length>262144)return;let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null)return;let r=n,o=typeof r.message=="object"&&r.message!==null?r.message:void 0,i=t==="model"?o?.model:r.version;return ee(i)?.slice(0,256)}function Eh(e,t,n){let r=ee(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=bc.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=bc.join(t.home_dir??ph.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=Sr.openSync(s,"r");try{let c=Sr.fstatSync(a).size,l=Math.min(c,wh),d=Buffer.alloc(l);Sr.readSync(a,d,0,l,Math.max(0,c-l));let u=d.toString("utf8").split(`
|
|
11
|
-
`).reverse();for(let f of u.slice(0,4096)){let
|
|
9
|
+
`}function J_(e,t={}){let n=Tn(e.metadata,t),r=oc(n),o=Wt(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=qm(s),c;try{c=Ho(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(!Xa(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!Xa(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 Me(e,t={}){let n=Ce(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=tc(t);return r==="toon"?Y_(e,o,t):K_(e,o,t)}function kt(e,t={}){return(t.format??"toon")==="toon"?J_(e,t):X_(e,t)}function _e(e,t={}){return{metadata:Tn(e.metadata,t),body:Wt(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 il from"fast-json-patch";import{AsyncLocalStorage as ph}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{}})();import yr from"node:fs";import Tt from"node:path";import{fileURLToPath as Q_}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 Z_="@unbrained/pm-cli";function eg(e){try{return JSON.parse(yr.readFileSync(e,"utf8")).name===Z_}catch{return!1}}function tg(e){let t=yr.existsSync(e)&&yr.statSync(e).isDirectory()?Tt.resolve(e):Tt.dirname(Tt.resolve(e));for(;;){let n=Tt.join(t,"package.json");if(yr.existsSync(n)&&eg(n))return t;let r=Tt.dirname(t);if(r===t)return;t=r}}function Yt(e,t=[]){let n=Q_(e),r=tg(n);return r||Tt.resolve(Tt.dirname(n),...t)}import{readFileSync as vg,readdirSync as qC,statSync as kg}from"node:fs";import H from"node:path";import sg 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 tt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ng(e){let t=e.key.trim();if(t.length===0)return null;let n=tt(e.aliases),r=e.description?.trim();return{key:t,values:tt(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 rg=e=>e,sc=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function og(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 ig(e,t){let n=new Map;for(let r of e??[]){let o=og(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 ic(e,t){return t?tt(e):void 0}function ei(e){let t=e?.trim();return t&&t.length>0?t:void 0}function br(e,t={}){let n=t.resolvePolicyCommand??rg,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=tt(e.aliases),l=(e.options??[]).map(u=>ng(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=ig(e.command_option_policies,n);return{name:r,description:ei(e.description),default_status:ei(e.default_status),folder:ei(e.folder),aliases:c.length>0?c:void 0,required_create_fields:ic(e.required_create_fields,o),required_create_repeatables:ic(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 ag=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],cg=["dep","comment","note","learning","file","test","doc"],ti=["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"],LC=["title","description","type","status","priority","tags","body",...ti,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],PC=["title","description","body","status","closeReason","priority","type","tags",...ti,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],cc={"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"},MC={...cc},FC={...cc},lc=[["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"]],dc=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function uc(e){return Object.fromEntries(e)}var $C=uc([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...lc,["author","--author"],["message","--message"],["dep","--dep"],...dc]),jC=uc([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...lc,...dc,["author","--author"],["message","--message"],["force","--force"]]);function wr(e){let t=lg(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function fc(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=sg.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 lg(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 dg(e){return br(e,{resolvePolicyCommand:sc})}function Sn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function ug(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:Sn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Sn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function fg(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 pg(e){if(Array.isArray(e.options))return e.options.map(t=>ug(t)).filter(t=>t!==null)}function mg(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>fg(t)).filter(t=>t!==null)}function _g(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:Sn(t,"aliases"),required_create_fields:Sn(t,"required_create_fields"),required_create_repeatables:Sn(t,"required_create_repeatables"),options:pg(t),command_option_policies:mg(t)}}function gg(e,t){return e.required_create_fields?tt(e.required_create_fields):t?.required_create_fields??[]}function hg(e,t){return e.required_create_repeatables?tt(e.required_create_repeatables):t?.required_create_repeatables??[]}function yg(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function bg(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function wg(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=fc(e.folder??t?.folder??wr(n)),s={name:n,folder:i,aliases:tt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:gg(e,t),required_create_repeatables:hg(e,t),options:yg(e,t),command_option_policies:bg(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function ac(e,t){for(let n of e){let r=dg(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,wg(r,i))}}function Eg(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=_g(o);i&&t.push(i)}}return t}function oe(e,t=null){let n=new Map;for(let c of Ta)n.set(c.toLowerCase(),{name:c,folder:we[c],aliases:[],required_create_fields:[...ag],required_create_repeatables:[...cg],options:[],command_option_policies:[]});ac(e.item_types?.definitions??[],n),ac(Eg(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 Tg={json_markdown:".md",toon:".toon"},Sg={".md":"json_markdown",".toon":"toon"};var Xt=[".md",".toon"];function Er(e){try{return kg(e),!0}catch{return!1}}function Ag(e){try{let t=JSON.parse(vg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function xg(e){let t=H.resolve(e);for(;;){let n=H.join(t,Ut),r=H.join(n,er);if(Er(r))return n;let o=H.join(t,er);if(Er(o)&&Ag(o))return t;let i=H.dirname(t);if(i===t)return;t=i}}function pc(e){return xg(e)??H.resolve(e,Ut)}function te(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=H.resolve(e,r);if(!Er(U(o))){let i=H.join(o,Ut);if(Er(U(i)))return i}return o}return pc(e)}function ni(e){let t=H.resolve(e),n=H.dirname(t);return H.basename(t)==="pm"&&H.basename(n)===".agents"?H.dirname(n):t}function U(e){return H.join(e,er)}function Cg(e,t,n=we){let r=n[t]??wr(t);return H.join(e,r)}function Jt(e,t,n,r="toon",o=we){return H.join(Cg(e,t,o),`${n}${Tg[r]}`)}function vr(e){let t=e.replaceAll("\\","/"),n=H.posix.extname(t).toLowerCase();return Sg[n]??null}function Fe(e,t){return H.join(e,"history",`${t}.jsonl`)}function mc(e,t){return H.join(e,"locks",`${t}.lock`)}function _c(e){return H.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 WC=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 St(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 gc=qt;function ri(e){let t=e.trim().toLowerCase();return gc.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 At(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ig(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function hc(e){return e?Ge(e):{}}function yc(e){return e?Ge(e):Ig()}function Ge(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]="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]="45d00ef3-870c-5f3f-89c1-6abd54c518fe")}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 oi=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"}]),Og=new Set(oi.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]="825e1dd9-4168-56f6-9183-b8cf75314b73")}catch{}})();var ii=[{kind:"blocked_by",direction:"directed",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",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",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",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",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",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]="7f733de4-104b-50a9-9c0a-cd9850bfcd78")}catch{}})();function kr(e){return e.trim().toLowerCase().replaceAll("-","_")}function Rg(e){if(e===void 0)return;let t=kr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function si(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)si(n,t);return Object.freeze(e)}for(let n of Object.values(e))si(n,t);return Object.freeze(e)}function Ng(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 Dg(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 Lg(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 Pg(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=kr(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 Mg(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}`)}function Fg(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}`)}var ai=class{#e=new Map;#t=new Map;constructor(t=ii){for(let n of t)this.register(n)}register(t){let n=Pg(t);if(Mg(t,n),Fg(t,n),Ng(t,n),Dg(t,n),Lg(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Rg(t.inverse),o=[...new Set((t.aliases??[]).map(kr))].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,hierarchy:t.hierarchy??!1,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?si(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=kr(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 Qt(){return new ai}var pI=Qt();(function(){try{var e=typeof window<"u"?window:typeof 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]="ac377139-8ce2-58ad-8005-0ac907a9baed")}catch{}})();var zg=5e3;async function wc(e,t,n){let r=[];for(let o of e)try{await o.run(Ge(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function qg(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 ci(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:Ge(t.before),after:t.after===null?null:Ge(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."]}))},zg),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)}qg(r,n,t.operation)}}async function li(e,t){return wc(e.onWrite,"onWrite",t)}async function di(e,t){return wc(e.onRead,"onRead",t)}function Bg(e){return{handled:!1,result:e.payload,warnings:[]}}function Gg(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Vg(e){return{service:e.service,command:e.command?At(e.command):void 0,args:e.args?Ge(e.args):void 0,options:e.options?hc(e.options):void 0,global:e.global?yc(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:Ge(e.payload)}}function Hg(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 Wg(e,t){return Hg(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 Kg(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&Ee(e,n.payload)}async function ui(e,t){let n=Gg(e,t.service);if(n.length===0)return Bg(t);let r=[];for(let o of n)try{let i=Vg(t),s=await Promise.resolve(o.run(i));if(Kg(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Wg(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}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]="c88047fc-2bbd-5781-96a8-01685c06fb33")}catch{}})();var iR=Object.freeze(Zn());(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 Tr=null;var mh=null;var _h=null,gh=null;var hh=[],yh=new ph;function nt(){return yh.getStore()}var bh=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function B(){let e=nt();return e?e.registrations:_h}function fi(e){if(!e)return;let t=nt();t?t.affectedItems.push(e):hh.push(e)}function Sr(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"||bh.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function ge(e){let t=nt(),n=t?t.hooks:Tr;return n?li(n,e):[]}async function pi(e){let t=nt(),n=t?t.hooks:Tr;n&&await ci(n,e)}async function Ie(e){let t=nt(),n=t?t.hooks:Tr;return n?di(n,e):[]}function Ar(){let e=nt();return((e?e.hooks:Tr)?.onRead?.length??0)>0}function wh(e,t){let n=nt(),r=n?n.commandContext:gh;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 $e(e,t){let n=nt(),r=n?n.services:mh;return r?ui(r,wh(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as bi}from"node:async_hooks";import{createHash as Ih}from"node:crypto";import Ir from"node:fs";import Oh from"node:os";import Ac from"node:path";import{AsyncLocalStorage as Eh}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 vh=new Eh,Tc=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function xr(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function An(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=xr(n.id,128),o=xr(n.parent_id,128);if(r===void 0||!Tc.test(r)||o!==void 0&&!Tc.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=xr(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function mi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=xr(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function kh(e,t,n){let r=vh.getStore(),o=mi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=An(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={...mi(r?.provenance),...o,...mi(e?.provenance)},a=An(e?.episode,!1)??An(n,!1)??i??An(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 Cr(e,t){return kh(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as _i,promises as OR,readFileSync as Th}from"node:fs";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]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var Sh="session.json";function gi(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Ah(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=gi(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=>gi(c,128)),a=t.focused_item_id===void 0||gi(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function xh(e){return Ve.join(_c(e),Sh)}function Ch(e,t){let n=t.PM_PATH?.trim();if(n){let o=Ve.resolve(e,n);if(_i(Ve.join(o,"settings.json")))return o;let i=Ve.join(o,".agents","pm");if(_i(Ve.join(i,"settings.json")))return i}let r=Ve.resolve(e);for(let o=0;o<32;o+=1){let i=Ve.join(r,".agents","pm");if(_i(Ve.join(i,"settings.json")))return i;let s=Ve.dirname(r);if(s===r)break;r=s}}function Sc(e){if(!e.key)return;let t=Ch(e.cwd,e.env);if(t)try{let n=JSON.parse(Th(xh(t),"utf8"));return Ah(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]="e0ab2d6f-0925-540d-8d24-a7f0687b4bf0")}catch{}})();var wi=["model","effort","role","topic","version"],Rr=new bi,Rh=new bi,Ei=new bi,Nh=[{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:{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:[]}],Dh=new Map,hi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ee(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function xt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function xc(e){let t=e.harness.trim().toLowerCase();if(!hi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:xt(e.environment_keys),model_environment_keys:xt(e.model_environment_keys),session_environment_keys:xt(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),xt(r)]).filter(([n])=>hi.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"&&hi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"))),provenance_unavailable_dimensions:xt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:xt(e.argv_markers).map(n=>n.toLowerCase()),client_names:xt(e.client_names).map(n=>n.toLowerCase())}}var Lh=Nh.map(xc);function Or(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function Cc(e=[]){let t=[...Lh,...[...Dh.values()].map(r=>r.descriptor),...Ei.getStore()?.descriptors??[],...e.map(xc)],n=new Set;for(let r of t){if(n.has(r.harness))throw new Error(`Harness signal descriptor collision for "${r.harness}"`);n.add(r.harness)}return t}function vi(e,t){for(let n of t??[]){let r=ee(e[n]);if(r)return r.slice(0,256)}}function Ph(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 Ic(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 ee(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return ee(i.slice(s.length+1))?.slice(0,256)}}var Mh=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Ct(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return Mh.has(n)?n:void 0}function yi(e,t){return ee(e?.[t])?.slice(0,256)}var Fh=1048576;function $h(e,t){if(e.length===0||e.length>262144)return;let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null)return;let r=n,o=typeof r.message=="object"&&r.message!==null?r.message:void 0,i=t==="model"?o?.model:r.version;return ee(i)?.slice(0,256)}function jh(e,t,n){let r=ee(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=Ac.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=Ac.join(t.home_dir??Oh.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=Ir.openSync(s,"r");try{let c=Ir.fstatSync(a).size,l=Math.min(c,Fh),d=Buffer.alloc(l);Ir.readSync(a,d,0,l,Math.max(0,c-l));let u=d.toString("utf8").split(`
|
|
11
|
+
`).reverse();for(let f of u.slice(0,4096)){let p=$h(f,e);if(p)return p}return}finally{Ir.closeSync(a)}}catch{return}}function Uh(e,t,n,r){let o=Ei.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(ee(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return jh(e,t,n);if(s==="ai_agent_version"){let a=ee(n.AI_AGENT);return!a||!r||!Or(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function zh(e,t,n){if(e==="ai_agent_version"){let r=ee(n.AI_AGENT);return r!==void 0&&Or(r,t.harness)}return ee(n.CLAUDE_CODE_SESSION_ID)!==void 0}function ki(e){return e||(Rh.getStore()??{env:process.env,argv:process.argv})}function qh(e,t,n,r){let o=e.environment_keys.some(a=>ee(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return Or(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||Or(r,a));return o||i||s}function Bh(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 Gh(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function Vh(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...wi,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=Ct(e,ee(n[s])?.slice(0,256)),d=Ct(e,Ic(t.argv??[],e)),l=Ct(e,Ph(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=yi(o?.provenance,e),_=Ct(e,vi(n,u[e])),g=Ct(e,yi(f,e)),b=Ct(e,yi(t.provenance,e)),E=Uh(e,t,n,r);return Gh([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[g,"mcp_client"],[b,"host"],[E,"probe"]])??Bh(e,i)??(l?{value:l,source:"argv"}:void 0)}function Hh(e,t){if(!(!e||!t))return Ih("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Wh(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...wi,...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=Vh(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 Ti(e){let t=ki(e),n=t.env??{},r=Cc(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(_=>qh(_,n,o,i)),a=Cr(t,n),c=[vi(n,s?.session_environment_keys),ee(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=Hh(s?.harness,c),d=Sc({cwd:t.cwd??process.cwd(),env:n,key:l}),u=Wh(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 Kh(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=zh(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 Si(e){let t=ki(e),n=Ti(t),r=Cc(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Ei.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(ee(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Cr(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,vi(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,Ic(t.argv??[],"role")].some(l=>{let d=ee(l)?.slice(0,256);return d!==void 0&&Ct("role",d)===void 0}),c=Object.fromEntries(wi.map(l=>[l,Kh(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function Yh(e,t,n){let r=ki(n),o=Ti(r);if(e!==void 0){let s=ee(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=ee(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=ee(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Oc(e){let t=Rr.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Rc(e){let t=Rr.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 Ai(e){let t=Rr.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Oe(e,t){let n=Yh(e,t);return Rr.enterWith(n),n.author}import xi from"node:fs/promises";import Zt from"node:path";import{createRequire as Xh}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 rt(e,t){let n=await V(e);if(n===null)return[];if(await Ie({path:e,scope:"project"}),n.trim()==="")return[];let r=Ce(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]="f1205949-16d8-51ce-98e8-04abc4c78ee8")}catch{}})();var Jh="history-event-index.sqlite",Qh="2";function Nc(e){return Zt.join(e,"runtime",Jh)}function Zh(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function ey(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?Zh(t):null}var Nr;function ty(){return Nr!==void 0||(Nr=ey(process.versions.node,Xh(import.meta.url))),Nr}function ny(e,t){e.prepare(`INSERT INTO events(
|
|
12
12
|
stream_id, stream_offset, ts, author, agent_harness,
|
|
13
13
|
agent_instance, op, entry_json
|
|
14
|
-
) 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 Ac(e,t){let n=Qt.dirname(Qt.dirname(e)),r=Sc(n);try{await ki.access(r)}catch{return}let o=$h();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Ph)throw new TypeError("Unsupported history event index version");let a=Qt.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);jh(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await ki.rm(r,{force:!0})}}async function Ir(e){await ki.rm(Sc(Qt.dirname(Qt.dirname(e))),{force:!0})}import Ci from"node:fs/promises";import en 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]="22af7808-6456-5889-b6e3-1abd73f35738")}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]="c873f95b-c435-5b0d-a631-565fb195b5cd")}catch{}})();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]="d059aa19-3822-5ff4-b4be-e2be8f537d1e")}catch{}})();function xc(e,t,n){if(e&&t)throw new y(`${n} cannot be combined with --full`,g.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var Uh=1,zh=4096;var MR=Object.freeze({version:Uh,max_length:zh});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c69ff43-7bbc-5128-9533-bbf15365126b")}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]="737ac274-c165-5d1a-8b8e-cb5d57a81c46")}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]="818ca284-2aaa-5d35-b280-8c963d443b0c")}catch{}})();var Bh=[...mn],Gh=[...Jn],Vh=[...To],Hh=[...So],Wh=[...Ao],Kh=[...xo],Or=["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 Cc=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Ic={help:"Commander help rendering has no SDK operation result.",item:"The item namespace only groups lifecycle subcommands already exposed as actions.",packages:"The plural package alias only renders package-oriented help."},Zt=Object.freeze(Or.flatMap(e=>e in Ic?[]:e==="extension"||e==="package"?[...Cc.map(t=>`${e}-${t}`),e]:[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]="23b3a820-f205-506b-9507-dbd60087f62e")}catch{}})();var Oc=["full","compact","brief","summary","counts"];var Yh=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"]),Xh=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Jh=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Qh={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Zh=3,ey=2;function Rc(e){let[t=""]=e.trim().split(/\s+/u);return Yh.has(t)?"mutation":Xh.has(t)?"discovery":Jh.has(t)?"governance":"read"}function Nc(e,t=Rc(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=Qh[t];return Dc({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*Zh/ey)},degradation_ladder:Oc,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Dc(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 Lc=Or.map(e=>Nc(e)),VR=new Map(Lc.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]="8e523bbc-5745-514e-a1d8-a6ad6ece001a")}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 Mc=256,Nr=1e4,ny=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,ry=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var nN=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&ny.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Mc,reason:`token_budget must be a safe integer of at least ${Mc}.`},{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<=Nr&&e.seen_item_ids.every(t=>typeof t=="string"&&ry.test(t)),reason:`seen_item_ids must contain at most ${Nr} 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]="e9621264-0180-53cf-862f-b59640b971da")}catch{}})();var Fc=["include","amount","cost","encoding"],$c=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","package-manage","comments-audit","assurance"],cy=["canonical","legacy","intent","default"],Ti={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},jc=Object.freeze(Fc.map(e=>Ti[e])),Uc=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),ly={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:{},"package-manage":{},"comments-audit":{},assurance:{}},dy=new Set(["--collapse","--fields","--section"]),zc=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 uy(e){return e.slice(2).replaceAll("-","_")}function fy(e,t){let n=zc[e];if(n!==void 0)return n;let r=t==="include"?dy.has(e)?"<csv>":uy(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Ti[t]} ${r}.`}function py(e){let t=ly[e],n=Object.freeze(Object.fromEntries(Fc.map(r=>[r,Object.freeze({dimension:r,canonical_option:Ti[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:zc[o]===void 0?"replacement":"behavior_preserving",migration_hint:fy(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:cy,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix"})}var my=Object.freeze($c.map(py)),SN=new Map(my.map(e=>[e.command,e]));function Rr(e){let t=e.trim().toLowerCase().replaceAll(/\s+/gu," "),n=t==="package manage"||t==="package-manage"?"package-manage":t.split(" ")[0],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return $c.includes(r)?r: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]="fa03d543-ff0d-5556-8558-9bed82838a58")}catch{}})();var FN=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:2400,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"}]),$N=new _y;(function(){try{var e=typeof window<"u"?window:typeof 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 s0}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 a0=new Set(Object.values(g));var qc=!1;function Si(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function hy(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function yy(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function Ai(e){if(e==="stdout"){hy();return}yy()}function Bc(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function by(){qc||(qc=!0,process.stdout.on("error",e=>{if(Si(e)){Ai("stdout");return}Bc(e)}),process.stderr.on("error",e=>{if(Si(e)){Ai("stderr");return}Bc(e)}))}function wy(e,t){by();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Si(n))return Ai(e),!1;throw n}}function xi(e){return wy("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 vy=en.join("runtime","history-drift-cache.json"),Vc={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 Hc(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function Ii(e){let t=en.join(e,vy),n=!1,r="invalid_cache_path";try{n=(await Ci.stat(await Ci.realpath(e))).isDirectory()}catch(o){let i=Hc(o);r=i===void 0?"unknown":Vc[i]??"filesystem_error"}if(!n){xi(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
15
|
-
`);return}try{await
|
|
16
|
-
`)}}async function He(e){let t=
|
|
14
|
+
) 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 Dc(e,t){let n=Zt.dirname(Zt.dirname(e)),r=Nc(n);try{await xi.access(r)}catch{return}let o=ty();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Qh)throw new TypeError("Unsupported history event index version");let a=Zt.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);ny(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await xi.rm(r,{force:!0})}}async function Dr(e){await xi.rm(Nc(Zt.dirname(Zt.dirname(e))),{force:!0})}import Ni from"node:fs/promises";import tn 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]="22af7808-6456-5889-b6e3-1abd73f35738")}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]="c873f95b-c435-5b0d-a631-565fb195b5cd")}catch{}})();import{AsyncLocalStorage as Ny}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]="d059aa19-3822-5ff4-b4be-e2be8f537d1e")}catch{}})();function Lc(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 ry=1,oy=4096;var cN=Object.freeze({version:ry,max_length:oy});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c69ff43-7bbc-5128-9533-bbf15365126b")}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]="737ac274-c165-5d1a-8b8e-cb5d57a81c46")}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]="818ca284-2aaa-5d35-b280-8c963d443b0c")}catch{}})();var sy=[..._n],ay=[...Qn],cy=[...Co],ly=[...Io],dy=[...Oo],uy=[...Ro],Lr=["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 Pc=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Mc={help:"Commander help rendering has no SDK operation result.",item:"The item namespace only groups lifecycle subcommands already exposed as actions.",packages:"The plural package alias only renders package-oriented help."},en=Object.freeze(Lr.flatMap(e=>e in Mc?[]:e==="extension"||e==="package"?[...Pc.map(t=>`${e}-${t}`),e]:[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]="23b3a820-f205-506b-9507-dbd60087f62e")}catch{}})();var Fc=["full","compact","brief","summary","counts"];var fy=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"]),py=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),my=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),_y={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},gy=3,hy=2;function $c(e){let[t=""]=e.trim().split(/\s+/u);return fy.has(t)?"mutation":py.has(t)?"discovery":my.has(t)?"governance":"read"}function jc(e,t=$c(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=_y[t];return Uc({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*gy/hy)},degradation_ladder:Fc,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Uc(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 zc=Lr.map(e=>jc(e)),hN=new Map(zc.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]="8e523bbc-5745-514e-a1d8-a6ad6ece001a")}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 Bc=256,Mr=1e4,by=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,wy=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var CN=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&by.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Bc,reason:`token_budget must be a safe integer of at least ${Bc}.`},{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<=Mr&&e.seen_item_ids.every(t=>typeof t=="string"&&wy.test(t)),reason:`seen_item_ids must contain at most ${Mr} 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]="e9621264-0180-53cf-862f-b59640b971da")}catch{}})();var Gc=["include","amount","cost","encoding"],Vc=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","package-manage","comments-audit","assurance"],Sy=["canonical","legacy","intent","default"],Ci={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},Hc=Object.freeze(Gc.map(e=>Ci[e])),Wc=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Ay={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:{},"package-manage":{},"comments-audit":{},assurance:{}},xy=new Set(["--collapse","--fields","--section"]),Kc=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 Cy(e){return e.slice(2).replaceAll("-","_")}function Iy(e,t){let n=Kc[e];if(n!==void 0)return n;let r=t==="include"?xy.has(e)?"<csv>":Cy(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Ci[t]} ${r}.`}function Oy(e){let t=Ay[e],n=Object.freeze(Object.fromEntries(Gc.map(r=>[r,Object.freeze({dimension:r,canonical_option:Ci[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:Kc[o]===void 0?"replacement":"behavior_preserving",migration_hint:Iy(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Sy,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix"})}var Ry=Object.freeze(Vc.map(Oy)),JN=new Map(Ry.map(e=>[e.command,e]));function Pr(e){let t=e.trim().toLowerCase().replaceAll(/\s+/gu," "),n=t==="package manage"||t==="package-manage"?"package-manage":t.split(" ")[0],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return Vc.includes(r)?r: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]="d09393aa-0253-5ad6-a2fe-245f31b9eb87")}catch{}})();var l0=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"}]),d0=new Ny;(function(){try{var e=typeof window<"u"?window:typeof 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 N0}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 D0=new Set(Object.values(h));var Yc=!1;function Ii(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Ly(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function Py(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function Oi(e){if(e==="stdout"){Ly();return}Py()}function Xc(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function My(){Yc||(Yc=!0,process.stdout.on("error",e=>{if(Ii(e)){Oi("stdout");return}Xc(e)}),process.stderr.on("error",e=>{if(Ii(e)){Oi("stderr");return}Xc(e)}))}function Fy(e,t){My();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Ii(n))return Oi(e),!1;throw n}}function Ri(e){return Fy("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 $y=tn.join("runtime","history-drift-cache.json"),Qc={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 Zc(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function Di(e){let t=tn.join(e,$y),n=!1,r="invalid_cache_path";try{n=(await Ni.stat(await Ni.realpath(e))).isDirectory()}catch(o){let i=Zc(o);r=i===void 0?"unknown":Qc[i]??"filesystem_error"}if(!n){Ri(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
15
|
+
`);return}try{await Ni.rm(t,{force:!0})}catch(o){let i=Zc(o);if(X(o))return;let s=i===void 0?"unknown":Qc[i]??"filesystem_error";Ri(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
16
|
+
`)}}async function He(e){let t=tn.dirname(tn.resolve(e));tn.basename(t)==="history"&&await Di(tn.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]="2fc7f675-3500-5abb-8d5c-9ca9caa803b6")}catch{}})();var Re=2,nn=[1,2];function Fr(e,t){return(e??"").localeCompare(t??"")}function el(e,t){return(e??0)-(t??0)}function ot(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function jy(e,t){return[e.scope.localeCompare(t.scope),Fr(e.path,t.path),Fr(e.command,t.command),el(e.timeout_seconds,t.timeout_seconds),Fr(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,ot(e.env_clear,t.env_clear,[]),ot(e.env_set,t.env_set,{}),ot(e.assert_stdout_contains,t.assert_stdout_contains,[]),ot(e.assert_stdout_regex,t.assert_stdout_regex,[]),ot(e.assert_stderr_contains,t.assert_stderr_contains,[]),ot(e.assert_stderr_regex,t.assert_stderr_regex,[]),el(e.assert_stdout_min_lines,t.assert_stdout_min_lines),ot(e.assert_json_field_equals,t.assert_json_field_equals,{}),ot(e.assert_json_field_gte,t.assert_json_field_gte,{}),Fr(e.note,t.note)].find(r=>r!==0)??0}function Uy(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function zy(e,t){let n=Uy(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 qy(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!zy(r,o.path)?{...o,op:"add"}:o;n.push(i),r=il.applyPatch(r,[i],!0,!0).newDocument}return n}function Li(e,t){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=_e(e),o=t===1&&r.metadata.tests?{...r.metadata,tests:[...r.metadata.tests].sort(jy)}:r.metadata;return{front_matter:Je(o,Ae),body:r.body}}function tl(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=_e(e);return{metadata:Je(n.metadata,Ae),body:n.body}}function xn(e,t){if(!nn.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return qe(R(Li(e,t)))}function Cn(e){let t=Li(e.before,Re),n=Li(e.after,Re),r=tl(e.before),o=tl(e.after),i=il.compare(r,o),s=qy(r,i),a=Rc(e.author),c=a.harness?Object.fromEntries(Object.entries(Si().provenance_outcomes).filter(([,d])=>d.status==="failed")):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??Oc(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:qe(R(t)),after_hash:qe(R(n)),item_hash_version:Re,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function nl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function By(e){let t=e.ts.trim();return t.length>0?t:F()}function rl(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function $r(e,t){let n=By(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(nl(r))return JSON.stringify(rl(r,n))}catch{}return e}return nl(e)?JSON.stringify(rl(e,n)):JSON.stringify(e)}async function jr(e,t){let n=await $e("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Gt(e,$r(n.result,t)),await He(e),await Dr(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 Gt(o,$r(r.line,t)),await He(o),await Dr(o);return}await Gt(o,$r(r.entry??t,t)),await He(o),await Dr(o);return}}await Gt(e,$r(t,t)),await He(e),await Dc(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 Mi={metadata:{},body:""};function In(){return structuredClone(Mi)}function ve(e,t=Re){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return xn(On(e),t)}catch{}return qe(R({replay_fallback:!0,metadata:e.metadata,body:e.body}))}function On(e){return{metadata:e.metadata,body:e.body}}function Fi(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=_e(e);return{metadata:Je(t.metadata,Ae),body:t.body}}function sl(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function Gy(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Rn(e){return Array.isArray(e)?e.filter(Gy).map(t=>({...t,path:sl(t.path),from:typeof t.from=="string"?sl(t.from):void 0})):[]}function Vy(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 rn(e,t){try{let n=Rn(t),r=Pi.applyPatch(structuredClone(e),n,!0,!1).newDocument;return Vy(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 Hy(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&nn.includes(t)))]}function Wy(e,t){return e!==void 0?[e]:t===void 0?[1,Re]:[t]}function It(e){let t=In(),n,r;for(let o=0;o<e.length;o+=1){let i=e[o],s=i.item_hash_version;if(s!==void 0&&!nn.includes(s))return{ok:!1,errors:[`verify_failed:unsupported_item_hash_version:${String(s)}:entry_${o+1}`]};let a=rn(t,i.patch);if(!a.ok)return{ok:!1,errors:[`verify_failed:patch_apply_failed:entry_${o+1}`]};let l=Wy(s,r).filter(u=>ve(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=>ve(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 Ot(e){let t=It(e);return{ok:t.ok,errors:t.errors}}function al(e,t){try{return{ok:!0,document:Pi.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function Ky(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Rn(t)){let c=al(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=al(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 $i(e){let t=Hy(e);if(t.length===1)return t[0];let n=It(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Re}function Ur(e,t=$i(e)){let n=e.findIndex(u=>u.item_hash_version!==void 0&&!nn.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=In(),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=ve(r,t),_=rn(r,f.patch),g,b,E=!1,v=0,C=0;if(_.ok)g=_.document,b=f.patch;else{let $=Ky(r,f.patch);g=$.document,b=Pi.compare(r,g),E=!0,v=$.convertedReplaceToAdd,C=$.skippedOps,c+=v,l+=C,a+=1}let A=ve(g,t),O=p!==f.before_hash||A!==f.after_hash;O&&(s+=1);let Q={...f,patch:b,before_hash:p,after_hash:A};d?Q.item_hash_version=t:delete Q.item_hash_version,o.push(Q),i.push({index:u+1,rehashed:O,patch_repaired:E,converted_replace_to_add:v,skipped_ops:C}),r=g}return{entries:o,finalDocument:r,entriesRehashed:s,entriesPatchRepaired:a,convertedReplaceToAdd:c,skippedOps:l,details:i,itemHashVersion:t,explicitItemHashVersion:d}}function it(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
17
17
|
`)}
|
|
18
|
-
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function
|
|
18
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c9d6924-ae7c-57c3-a346-1e2189c532fa")}catch{}})();function ji(e,t){let n=Ce(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 st(e){return R({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Yy(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&st(e[r])===st(t[r]);)r+=1;return r}function Vi(e,t,n){ji(e,"base");let r=ji(t,"ours"),o=ji(n,"theirs"),i=Yy(r,o);if(i===r.length&&i===o.length)return{merged:it(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:it(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:it(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(st)),c=o.slice(i).filter(u=>!a.has(st(u))),l=[...s,...c].sort((u,f)=>{let p=ae(u.ts,f.ts);if(p!==0)return p;let _=a.has(st(u)),g=a.has(st(f));return _!==g?Number(g)-Number(_):st(u).localeCompare(st(f))}),d=Ur([...r.slice(0,i),...l]);return{merged:it(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 Ui(e,t){let n=Ce(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 zr(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
19
19
|
`)}
|
|
20
|
-
`}function
|
|
21
|
-
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as
|
|
22
|
-
`);let s=await
|
|
23
|
-
`)}return i}async function
|
|
24
|
-
`);let r=await
|
|
25
|
-
`)}}}async function By(e){let t=await rn(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:F()}}import{readFile as vw,writeFile as Ew}from"node:fs/promises";import kw 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 Nt=new Set(Ae),Gy=Object.freeze({get size(){return Nt.size},has(e){return Nt.has(e)},entries(){return Nt.entries()},keys(){return Nt.keys()},values(){return Nt.values()},forEach(e,t){Nt.forEach(n=>e.call(t,n,n,Gy))},[Symbol.iterator](){return Nt.values()}});function Vy(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Hy(e){return typeof e!="string"?null:Zo(e)}function Wy(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Vy(r.name),i=Hy(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}`,g.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function We(e){return[...Wy(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]="027f6acb-15cc-5707-85ed-b5298b6b6abe")}catch{}})();var ne={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ne,R=e=>typeof e=="boolean"?{ok:!0,value:e}:ne;function M(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?ne:{ok:!0,value:t}}function D(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ne}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ne;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ne;r.push(i.value)}return{ok:!0,value:r}}}function Yi(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}:ne}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Ur(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ne;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ne;n[r]=i.value}return{ok:!0,value:n}}}function x(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ne;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ne;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var Ky=x({key:w,values:k(w),required:p(R),aliases:p(k(w)),description:p(w)}),Yy=x({command:D("create","update"),option:w,required:p(R),visible:p(R),enabled:p(R)}),Xy=x({name:w,description:p(w),default_status:p(w),folder:p(w),aliases:p(k(w)),required_create_fields:p(k(w)),required_create_repeatables:p(k(w)),options:p(k(Ky)),command_option_policies:p(k(Yy))}),Jy=x({id:w,aliases:p(k(w)),roles:p(k(D(...er))),description:p(w),order:p(M())}),Qy=x({key:w,metadata_key:p(w),front_matter_key:p(w),cli_flag:p(w),cli_aliases:p(k(w)),description:p(w),type:p(D(...zt)),commands:p(k(D(...tr))),repeatable:p(R),required:p(R),required_on_create:p(R),required_types:p(k(w)),allow_unset:p(R)}),Zy=e=>{if(!Array.isArray(e)||e.length!==2)return ne;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ne:{ok:!0,value:[t,n]}},eb=x({type:w,allowed_transitions:k(Zy)}),tb=p(x({version:p(M({int:!0})),files:p(x({types:p(w),statuses:p(w),fields:p(w),workflows:p(w)})),statuses:p(k(Jy)),fields:p(k(Qy)),workflow:p(x({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(k(eb)),unknown_field_policy:p(D(...nr))})),nb=p(x({preset:p(D(...wa)),ownership_enforcement:p(D("none","warn","strict")),create_mode_default:p(D("progressive","strict")),close_validation_default:p(D("off","warn","strict")),require_close_reason:p(R),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),force_required_for_stale_lock:p(R),create_default_type:p(w),workflow_enforcement:p(D("off","warn","strict")),duplicate_detection_mode:p(D("off","advisory","strict")),duplicate_detection_threshold:p(M({min:0,max:1})),duplicate_detection_limit:p(M({int:!0,min:0,max:20}))})),rb=x({name:w,disabled:p(R),require_trusted:p(R),require_provenance:p(R),sandbox_profile:p(D("none","restricted","strict")),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w))}),Ki=D("block","warn"),ob=e=>typeof e=="string"?Ki(e):x({global:p(Ki),project:p(Ki)})(e),ib=p(x({mode:p(D("off","warn","enforce")),trust_mode:p(D("off","warn","enforce")),pm_max_version_exceeded_mode:p(ob),require_provenance:p(R),trusted_extensions:p(k(w)),default_sandbox_profile:p(D("none","restricted","strict")),allowed_extensions:p(k(w)),blocked_extensions:p(k(w)),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w)),extension_overrides:p(k(rb))})),Dt=Yi(128),sb=x({harness:Yi(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Dt,64)),model_environment_keys:p(k(Dt,64)),session_environment_keys:p(k(Dt,64)),provenance_environment_keys:p(Ur(k(Dt,64))),provenance_resolvers:p(Ur(D("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Dt,64)),argv_markers:p(k(Dt,64)),client_names:p(k(Dt,64))}),ab=x({version:M({int:!0}),id_prefix:w,ids:p(x({token_length:p(M({int:!0,min:4,max:12}))})),author_default:w,agent_identity:p(x({probes_enabled:p(R),identity_vocabulary:p(x({version:M({int:!0,positive:!0}),aliases:Ur(Yi(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(sb)})),mutation_guard:p(x({require_attributed_author:p(R),secret_guard:p(D("off","advise","block")),stale_in_progress_hours:p(M({int:!0,positive:!0}))})),item_format:p(D("toon","json_markdown")),locks:x({ttl_seconds:M({int:!0}),wait_ms:p(M({int:!0,min:0}))}),checkpoints:p(x({retention_days:p(M({int:!0,positive:!0}))})),output:x({default_format:D("toon","json")}),history:p(x({missing_stream:D("auto_create","strict_error"),compact_policy:p(x({enabled:p(R),max_entries:p(M({int:!0,positive:!0})),trigger:p(D("health_warn","auto"))}))})),validation:p(x({sprint_release_format:D("warn","strict_error"),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),metadata_required_fields:p(k(w)),lifecycle_stale_blocker_reason_patterns:p(k(w)),lifecycle_closure_like_blocked_reason_patterns:p(k(w)),lifecycle_closure_like_resolution_patterns:p(k(w)),lifecycle_closure_like_actual_result_patterns:p(k(w)),estimate_defaults_by_type:p(Ur(M({int:!0,positive:!0})))})),governance:nb,workflow:p(x({definition_of_done:k(w)})),testing:p(x({record_results_to_items:R})),telemetry:p(x({enabled:R,first_run_prompt_completed:p(R),capture_level:p(D("minimal","redacted","max")),endpoint:p(w),installation_id:p(w),retention_days:p(M({int:!0,positive:!0}))})),agent_guidance:p(x({prompt_completed:p(R),declined:p(R),declined_at:p(w),template_version:p(M({int:!0,positive:!0})),last_checked_files:p(k(w))})),item_types:p(x({definitions:k(Xy)})),schema:tb,context:p(x({default_depth:p(D("brief","standard","deep")),activity_limit:p(M({int:!0,positive:!0})),stale_threshold_days:p(M({int:!0,positive:!0})),sections:p(x({hierarchy:p(R),activity:p(R),progress:p(R),recently_created:p(R),unparented:p(R),blockers:p(R),files:p(R),workload:p(R),staleness:p(R),tests:p(R)}))})),extensions:x({enabled:k(w),disabled:k(w),policy:ib}),search:x({score_threshold:M(),hybrid_semantic_weight:p(M()),max_results:M({int:!0}),embedding_model:w,embedding_corpus_max_characters:p(M()),embedding_batch_size:M({int:!0}),embedding_timeout_ms:p(M({int:!0})),scanner_max_batch_retries:M({int:!0}),provider:p(w),corpus_fields:p(k(w)),mutation_refresh_policy:p(D("cache_only","semantic_configured","semantic_auto")),query_expansion:p(x({enabled:p(R),provider:p(w)})),rerank:p(x({enabled:p(R),model:p(w),top_k:p(M({int:!0,positive:!0}))})),bm25:p(x({k1:p(M()),b:p(M())}))}),providers:x({openai:x({base_url:w,api_key:w,model:w}),ollama:x({base_url:w,model:w})}),vector_store:x({adapter:p(w),collection_name:p(w),qdrant:x({url:w,api_key:w}),lancedb:x({path:w})})});function ul(e){let t=ab(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Rn from"node:path";import Ke from"node:fs/promises";import Xi from"node:path";import{randomUUID as cb}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 lb(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 _l(e){try{let t=await Ke.readFile(e,"utf8");return await Ie({path:e,scope:"project"}),lb(t)}catch(t){return X(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Ji(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function gl(e,t){await ge({path:e,scope:"project",op:t})}function db(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:F(),ttl_seconds:n}}async function ub(e,t,n,r){await Ke.mkdir(Xi.dirname(e),{recursive:!0});let o=await Ke.open(e,"wx");try{await o.writeFile(`${JSON.stringify(db(t,n,r),null,2)}
|
|
26
|
-
`,"utf8")}finally{await o.close()}await
|
|
27
|
-
`,"utf8")}catch{return await Qi(e),null}return t}async function Ab(e){let t;try{let r=await Ke.stat(e);if(t=Date.now()-r.mtimeMs,t<=yb)return!1}catch(r){return X(r)}let n=await vl(e);return n!==null&&Sb(n.pid)&&t<=bb?!1:Qi(e)}async function xb(e,t){let n=`${e}${hb}`,r=await ml(n);if(r!==null)return async()=>pl(n,r.token);if(!await Ab(n))return null;let o=await ml(n);return o===null?null:async()=>pl(n,o.token)}async function Cb(e){let t=await xb(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await _l(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!yl(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(kb(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=gb)throw wl(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await hl(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function Ne(e,t,n,r,o=!1,i=!0,s){let a=await $e("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=Eb(a.result);if(m)return async()=>{await Promise.resolve(m()),await $e("lock_release",{pm_root:e,id:t,owner:r})}}let c=ac(e,t),l=wb(s),d=Date.now(),u=0,f=pb;for(;;)try{return await ub(c,t,r,n),async()=>{await hl(c,"lock:release"),await $e("lock_release",{pm_root:e,id:t,owner:r})}}catch(m){if(!Ji(m,"EEXIST"))throw new y(`Failed to acquire lock for ${t}: ${Be(m)}`,g.GENERIC_FAILURE);let _=await _l(c);if(yl(_.info,n)){let b=await Cb({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 h=Date.now()-d;if(l===0||h>=l)throw wl(t,_.info,l===0?0:h);await vb(Math.min(f,l-h)),f=Math.min(f*2,mb)}}(function(){try{var e=typeof window<"u"?window:typeof 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 le="_workspace";function zr(e){return Rn.join(e,"history",`${le}.jsonl`)}function Ib(e,t=e.length){let n=Cn();for(let r of e.slice(0,t))n=nn(n,r.patch).document;return In(n)}function Ob(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Rb(e){throw new y(`Workspace history verification failed: ${e.join(", ")}`,g.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Nb(e,t){let n=Rn.resolve(t),r=Rn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Rn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Zi(e){let t=await rt(zr(e),le),n=It(t);n.ok||Rb(n.errors);let r=Ob(t.length===0?No:Ib(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=Nb(e,Rn.resolve(e,c));if(l=await V(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(P(u)===P(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 Db={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},El=120;function es(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Tl(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var Lb=Tl(Db),kl=new WeakMap;function Pb(e){let t=kl.get(e);if(t)return t;let n=Tl(e);return kl.set(e,n),n}function Sl(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return El;if(t){let o=Pb(t).get(n);if(es(o))return Math.floor(o)}let r=Lb.get(n);return es(r)?Math.floor(r):El}function Al(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||!es(r)||(t[o]=Math.floor(r))}return t}import{stat as Mb}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 qr=new Map;function xl(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function Fb(e){try{let t=await Mb(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function at(e){let t=xl(e),n=await Promise.all(t.map(r=>Fb(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Nn(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 Cl(e){return qr.get(e)}function Br(e,t){let n=xl(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));qr.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Lt(e){if(e){qr.delete(e);return}qr.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]="a434b9ea-4692-51c5-8761-0f1759fff394")}catch{}})();var Rl=Symbol("pm.settings.persist_source"),jb=128,Ub=new Set(["off","advisory","strict"]);function Il(e){return structuredClone(Oo[e])}function zb(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:Z.governance.preset}function qb(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),Ub.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 Pt(e){let t=e.governance??{},n=zb(t.preset),r=qb(t);if(n==="custom"){let s=Il("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=Il(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Nl(){return structuredClone(Z)}function Bb(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:Z.search.mutation_refresh_policy}function Gb(e){return typeof e=="boolean"?e:Z.search.query_expansion.enabled}function Vb(e){return typeof e!="string"?Z.search.query_expansion.provider:e.trim()}function Hb(e){return typeof e=="boolean"?e:Z.search.rerank.enabled}function Wb(e){return typeof e!="string"?Z.search.rerank.model:e.trim()}function Kb(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:Z.search.rerank.top_k}function Yb(e){if(typeof e!="string")return Z.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,jb);return n.length>0?n:Z.vector_store.collection_name}function ts(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Xb(e,t){let n=e.schema,r=ts(n?.statuses),o=ts(n?.fields),i=ts(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Hr(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:Hr(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 Dl(e,t){Object.defineProperty(e,Rl,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Jb(e){let t=e[Rl];if(!(!t||typeof t!="object"))return t}function Vr(e){let t=structuredClone(e.settings),n=Jb(e.settings);return n&&Dl(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function Qb(e,t,n){let r=Je(t);return[n,me(e,r.files.types,ae.types),me(e,r.files.statuses,ae.statuses),me(e,r.files.fields,ae.fields),me(e,r.files.workflows,ae.workflows)]}async function Zb(e,t,n){let r=await at(t);Br(e,{tracked_paths:t,signatures:r,value:Vr(n)})}async function ew(e,t,n){try{await Zb(e,t,n)}catch{Lt(e)}}function Ol(e,t){return e.find(n=>n.path===t)}function tw(e,t,n){for(let r of n){let o=Ol(e,r),i=Ol(t,r);if(!o||!i||!Nn([o],[i]))return!1}return!0}async function ns(e,t,n,r,o){try{let i=await at(t);if(!tw(r,i,o)){Lt(e);return}Br(e,{tracked_paths:t,signatures:i,value:Vr(n)})}catch{Lt(e)}}function Dn(e){return{settings:Nl(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function nw(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function rw(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ow(e){let t=Z.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:rw(e?.last_checked_files??t.last_checked_files)}}function De(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function iw(e){return e==="off"||e==="warn"||e==="enforce"?e:Z.extensions.policy.mode}function sw(e){return e==="off"||e==="warn"||e==="enforce"?e:Z.extensions.policy.trust_mode}function Ll(e){return e==="none"||e==="restricted"||e==="strict"?e:Z.extensions.policy.default_sandbox_profile}function aw(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=Ll(e.sandbox_profile));let r=De(e.allowed_capabilities),o=De(e.blocked_capabilities),i=De(e.allowed_surfaces),s=De(e.blocked_surfaces),a=De(e.allowed_commands),c=De(e.blocked_commands),l=De(e.allowed_actions),d=De(e.blocked_actions),u=De(e.allowed_services),f=De(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 cw(e){let t=new Map;for(let n of e??[]){let r=aw(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function rs(e){return e==="block"||e==="warn"?e:void 0}function lw(e){if(typeof e=="string")return rs(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=rs(e.global),n=rs(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function ye(e,t){return De(e?.[t]??Z.extensions.policy[t])}function dw(e){let t=lw(e?.pm_max_version_exceeded_mode);return{mode:iw(e?.mode),trust_mode:sw(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ye(e,"trusted_extensions"),default_sandbox_profile:Ll(e?.default_sandbox_profile),allowed_extensions:ye(e,"allowed_extensions"),blocked_extensions:ye(e,"blocked_extensions"),allowed_capabilities:ye(e,"allowed_capabilities"),blocked_capabilities:ye(e,"blocked_capabilities"),allowed_surfaces:ye(e,"allowed_surfaces"),blocked_surfaces:ye(e,"blocked_surfaces"),allowed_commands:ye(e,"allowed_commands"),blocked_commands:ye(e,"blocked_commands"),allowed_actions:ye(e,"allowed_actions"),blocked_actions:ye(e,"blocked_actions"),allowed_services:ye(e,"allowed_services"),blocked_services:ye(e,"blocked_services"),extension_overrides:cw(e?.extension_overrides??Z.extensions.policy.extension_overrides)}}function uw(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 Gr(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function fw(e){return Array.isArray(e)?e:[]}function pw(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:uw(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Gr(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Gr(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Gr(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Gr(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Al(e.validation?.estimate_defaults_by_type)}}function mw(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 _w(e,t){return{...t.search,...e.search,mutation_refresh_policy:Bb(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Gb(e.search?.query_expansion?.enabled),provider:Vb(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Hb(e.search?.rerank?.enabled),model:Wb(e.search?.rerank?.model),top_k:Kb(e.search?.rerank?.top_k)}}}function gw(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Yb(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function hw(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function yw(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 bw(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Hr(e){let t=(e??[]).map(r=>_r(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 ww(e){let t=Nl(),n=Pt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:hw(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},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:pw(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},telemetry:mw(e,t),agent_guidance:ow(e.agent_guidance??t.agent_guidance),item_types:{definitions:Hr(e.item_types?.definitions)},schema:Je(e.schema??t.schema),context:yw(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:dw(e.extensions.policy??t.extensions.policy)},search:_w(e,t),providers:bw(e,t),vector_store:gw(e,t)}}async function Ln(e){let t=U(e),n=[t];await Ie({path:t,scope:"project"});let r=Cl(e);if(r){let l=await at(r.tracked_paths);if(Nn(l,r.signatures))return Vr(r.value)}let o=await at([t]),i;try{i=await V(t)}catch{return Dn("settings_read_fs_error")}if(i===null){let l=Dn();return await ns(e,[t],l,o,[t]),l}let s=await at([t]);if(!Nn(o,s))return Lt(e),Ln(e);let a;try{a=JSON.parse(i)}catch{let l=Dn("settings_read_invalid_json");return await ns(e,[t],l,s,[t]),l}let c=ul(a);if(!c.success){let l=Dn("settings_read_invalid_schema");return await ns(e,[t],l,s,[t]),l}try{let l=ww(c.data),d=Qb(e,l.schema,t);n=d;let u=await at(d),f=await Ra(e,l.schema),m=await Na(e,l.schema),_=await at(d),h={...l,item_types:{definitions:Hr([...l.item_types.definitions,...fw(m.type_definitions_from_file)])},schema:m.schema};Dl(h,Xb(c.data,h));let b={settings:h,metadata:{has_explicit_item_format:nw(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(v=>`runtime_schema_bootstrap_created:${v}`),...m.warnings]};return f.created_paths.length===0?Nn(u,_)?Br(e,{tracked_paths:d,signatures:_,value:Vr(b)}):Lt(e):Lt(e),b}catch{let l=Dn("settings_read_merge_failed");return await ew(e,n,l),l}}async function W(e){return(await Ln(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 is=["item","history","relationship","json"];function Tw(e){let t=e.trim().toLowerCase();if(is.includes(t))return t;throw new y(`Unknown merge artifact "${e}". Supported values: ${is.join(", ")}.`,g.USAGE)}function Sw(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.`,g.USAGE)}async function os(e,t){try{return await vw(e,"utf8")}catch{throw new y(`Cannot read merge ${t} file at ${e}.`,g.NOT_FOUND)}}async function Aw(e){let t=te(process.cwd(),e.path);return await N(U(t))?W(t):null}function xw(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Cw(e,t){let n=Tw(e.artifact),r=Sw(e.prefer),o=kw.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([os(e.basePath,"base"),os(e.oursPath,"ours"),os(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let m=zi(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=qi(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 Aw(t),_=Bi(i,s,a,{format:xw(e.itemPath??o,m),schema:m?.schema,extensionFieldNames:We(B()),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=Gi(i,s,a,{preferred:r});c=m.merged,d.push(...m.conflict_paths),u.json={paths_from_theirs:m.paths_from_theirs}}if(await Ew(o,c,"utf8"),l!==void 0){let m=await dl(l);m!==null&&(u.receipt=Rt(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:F()}}import{readFile as Kr,realpath as ss,writeFile as Nw}from"node:fs/promises";import{execFile as Dw}from"node:child_process";import G from"node:path";import{promisify as Lw}from"node:util";import Iw 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 Pl=["runtime/","search/","locks/","transactions/","checkpoints/"];function Ml(e){let t=e.replaceAll("\\","/");return Iw.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 Ow="PM_SOURCE_CONTEXT_ACCESS",Rw="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Fl(e){let t=e[Ow],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Rw]?.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]="5e1810a5-04b8-5929-8eee-7a63f1684860")}catch{}})();var as=Lw(Dw),Pn="# pm-cli:merge-drivers:start",cs="# pm-cli:merge-drivers:end",Mt="# pm-cli:merge-drivers:v2:start",Wr="# pm-cli:merge-drivers:v2:end",Pw="merge-fence";function $l(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function zl(){let e=Kt(import.meta.url,["../../.."]);return`${$l(process.execPath)} ${$l(G.join(e,"dist","cli.js"))}`}var ql=[{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 Bl(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Fl(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=te(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:G.resolve(r),workspace_start:G.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?te(e.cwd,".agents/pm"):te(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function on(e){try{let{stdout:t}=await as("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ss(t.trim())}catch{return null}}async function Gl(e){let t=await on(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function ls(e,t){return G.relative(e,t).replaceAll("\\","/")}function je(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function jl(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 Mw(e,t){let n=jl(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=jl(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(G.basename(n.value))||G.basename(r.value)!=="cli.js"||G.basename(G.dirname(r.value))!=="dist"||!await N(n.value)||!await N(r.value))return!1;try{let o=G.dirname(G.dirname(r.value)),i=JSON.parse(await Kr(G.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 Yr(e,t){let n=e.length>0?`${e}/`:"",r=[`${je(`${n}**/*.toon`)} merge=pm-item-toon`,`${je(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${je(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${je(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${je(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${je(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${je(`${n}settings.json`)} merge=pm-json`),r.push(`${je(`${n}**/*.json`)} merge=pm-json`),r.push(`${je(`${n}extensions/**`)} -merge`),r.push(`${je(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Ul(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 Vl(e,t,n){let r=G.join(e,".gitattributes"),o="";try{o=await Kr(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&X(l)))throw l}let i=[Mt,...t,Wr].join(`
|
|
28
|
-
`),a=
|
|
20
|
+
`}function Xy(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Hi(e,t,n){Ui(e,"base");let r=Ui(t,"ours"),o=Ui(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:zr(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:zr(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:zr(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=ae(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=Xy([...r.slice(0,s),...d]);return{merged:zr(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var cl=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],ll=["updated_at"];function Rt(e,t){return R(e??null)===R(t??null)}function Jy(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(d=>R(d))),i=r(t),s=new Set(i.map(d=>R(d))),a=r(n),c=new Set(a.map(d=>R(d))),l=i.filter(d=>{let u=R(d);return!o.has(u)||c.has(u)});for(let d of a){let u=R(d);!s.has(u)&&!o.has(u)&&l.push(d)}return l}function Qy(e,t){return ae(String(e),String(t))>=0?e:t}function dl(e,t,n,r){return Rt(t,n)?{value:t,from_theirs:!1,conflict:!1}:Rt(e,t)?{value:n,from_theirs:!0,conflict:!1}:Rt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function ul(e,t,n,r,o){let i=dl(e,t,n,r);if(!i.conflict||o==="preferred_side")return i;let s=R(n).localeCompare(R(t))<0;return{value:s?n:t,from_theirs:s,conflict:!0}}function zi(e){return{...e.metadata}}function qi(e,t,n){try{return _e(Me(e,n),n)}catch(r){throw new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,h.GENERIC_FAILURE)}}function Zy(e,t,n,r,o){let i=new Set(cl),s=new Set(ll),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(i.has(l)){let _=Jy(d,u,f);c.merged[l]=_,Rt(_,u)||c.unionFields.push(l);continue}if(s.has(l)){c.merged[l]=Qy(u,f);continue}let p=ul(d,u,f,r,o);p.value!==void 0&&(c.merged[l]=p.value),p.conflict?(c.conflictFields.push(l),c.conflictDecisions.push({field:l,base:d,ours:u,theirs:f,retained:p.value,discarded:p.from_theirs?u:f})):p.from_theirs&&c.fieldsFromTheirs.push(l)}return c}function Wi(e,t,n,r={}){let o=r.preferred??"ours",i=r.conflictResolution??"preferred_side",s=e.trim().length>0,a=qi(t,"ours",r),c=qi(n,"theirs",r),l=s?qi(e,"base",r):a,d=s?zi(l):{},u=zi(a),f=zi(c),{merged:p,conflictFields:_,fieldsFromTheirs:g,unionFields:b,conflictDecisions:E}=Zy(d,u,f,o,i),v=ul(s?l.body:"",a.body,c.body,o,i);return v.conflict?(_.push("body"),E.push({field:"body",base:s?l.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&g.push("body"),{merged:kt({metadata:p,body:v.value},r),conflict_fields:_,fields_from_theirs:g,union_fields:b,conflict_decisions:E,requested_preference:o,conflict_resolution:i}}function Bi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gi(e,t){let n=Ce(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 eb(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=R(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=R(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 tb(e,t,n,r,o,i,s){if(!Bi(t)||!Bi(n))return null;let a=Bi(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=nb(a,t,n,d,r,u,i,s);f!==void 0&&(c[d]=f)}return c}function fl(e,t,n,r,o,i,s){if(Rt(t,n))return t;let a=eb(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(o),a.merged;let c=tb(e,t,n,r,o,i,s);if(c!==null)return c;let l=dl(e,t,n,r);return l.conflict?i.push(o):l.from_theirs&&s.push(o),l.value}function nb(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 fl(e[r],t[r],n[r],o,i,s,a);if(c){if(d&&Rt(e[r],t[r])){a.push(i);return}return d?(s.push(i),o==="theirs"?void 0:t[r]):t[r]}if(!(d&&Rt(e[r],n[r])))return d?(s.push(i),o==="theirs"?n[r]:void 0):(a.push(i),n[r])}function Ki(e,t,n,r={}){let o=r.preferred??"ours",i=Gi(e,"base"),s=Gi(t,"ours"),a=Gi(n,"theirs"),c=[],l=[],d=fl(i,s,a,o,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
|
|
21
|
+
`,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as rb}from"node:child_process";import{randomUUID as ob}from"node:crypto";import{readdir as ib,readFile as _l}from"node:fs/promises";import he from"node:path";import{promisify as sb}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]="7b87b458-164a-5332-8803-6b0695481644")}catch{}})();var ab=sb(rb);async function Yi(e){try{let{stdout:t}=await ab("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 gl(e,t){let n=he.dirname(he.resolve(e,t));for(let r=0;r<12;r+=1){if(await D(he.join(n,"settings.json")))return n;let o=he.dirname(n);if(o===n)break;n=o}return null}function Xi(e){return he.join(e,"merge-receipts")}function qr(e){return`${e}.json`}function Nt(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:pl(t.retained)??qe(R(t.retained)),discarded_hash:pl(t.discarded)??qe(R(t.discarded))}))}}function pl(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}async function hl(e){let t=await Yi(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=he.basename(r,he.extname(r)),i={version:1,id:ob(),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],decisions:structuredClone(e.decisions),state:"pending",created_at:F(),value_availability:"clone_local"};await wt(t),await P(he.join(t,qr(i.id)),`${JSON.stringify(i,null,2)}
|
|
22
|
+
`);let s=await gl(e.cwd,i.item_path);if(s!==null){let a=Xi(s),c=Nt(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 wt(a),await P(he.join(a,qr(i.id)),`${JSON.stringify(l,null,2)}
|
|
23
|
+
`)}return i}async function ml(e,t){if(!await D(e))return[];let n;try{n=await ib(e)}catch{return[]}let r=[];for(let o of n.sort((i,s)=>i.localeCompare(s)))if(o.endsWith(".json"))try{let i=JSON.parse(await _l(he.join(e,o),"utf8")),{preferred:s,...a}=i,c={...a,requested_preference:i.requested_preference??s??"ours",conflict_resolution:i.conflict_resolution??"preferred_side"};c.version===1&&(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)&&r.push(c)}catch{}return r}async function on(e,t={}){let n=await Yi(e),r=n===null?[]:await ml(n,t),o=t.pmRoot??he.join(e,".agents","pm"),i=await ml(Xi(o),t),s=new Map(i.map(a=>[a.id,a]));for(let a of r)s.set(a.id,a);return[...s.values()].sort((a,c)=>a.created_at.localeCompare(c.created_at))}function Br(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 Ji(e,t){let n=await Yi(e);if(n===null)return;await P(he.join(n,qr(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:F()},null,2)}
|
|
24
|
+
`);let r=await gl(e,t.item_path);if(r!==null){let o=he.join(Xi(r),qr(t.id));if(await D(o)){let i=JSON.parse(await _l(o,"utf8"));await P(o,`${JSON.stringify({...i,state:"reconciled",reconciled_at:F()},null,2)}
|
|
25
|
+
`)}}}async function cb(e){let t=await on(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:F()}}import{readFile as Uw,writeFile as zw}from"node:fs/promises";import qw 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 Dt=new Set(Ae),lb=Object.freeze({get size(){return Dt.size},has(e){return Dt.has(e)},entries(){return Dt.entries()},keys(){return Dt.keys()},values(){return Dt.values()},forEach(e,t){Dt.forEach(n=>e.call(t,n,n,lb))},[Symbol.iterator](){return Dt.values()}});function db(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ub(e){return typeof e!="string"?null:ri(e)}function fb(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=db(r.name),i=ub(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 We(e){return[...fb(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]="027f6acb-15cc-5707-85ed-b5298b6b6abe")}catch{}})();var ne={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ne,N=e=>typeof e=="boolean"?{ok:!0,value:e}:ne;function M(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?ne:{ok:!0,value:t}}function L(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ne}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ne;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ne;r.push(i.value)}return{ok:!0,value:r}}}function Zi(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}:ne}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Gr(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ne;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ne;n[r]=i.value}return{ok:!0,value:n}}}function x(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ne;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ne;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var pb=x({key:w,values:k(w),required:m(N),aliases:m(k(w)),description:m(w)}),mb=x({command:L("create","update"),option:w,required:m(N),visible:m(N),enabled:m(N)}),_b=x({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(k(w)),required_create_fields:m(k(w)),required_create_repeatables:m(k(w)),options:m(k(pb)),command_option_policies:m(k(mb))}),gb=x({id:w,aliases:m(k(w)),roles:m(k(L(...tr))),description:m(w),order:m(M())}),hb=x({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(k(w)),description:m(w),type:m(L(...qt)),commands:m(k(L(...nr))),repeatable:m(N),required:m(N),required_on_create:m(N),required_types:m(k(w)),allow_unset:m(N)}),yb=e=>{if(!Array.isArray(e)||e.length!==2)return ne;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ne:{ok:!0,value:[t,n]}},bb=x({type:w,allowed_transitions:k(yb)}),wb=m(x({version:m(M({int:!0})),files:m(x({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(k(gb)),fields:m(k(hb)),workflow:m(x({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(k(bb)),unknown_field_policy:m(L(...rr))})),Eb=m(x({preset:m(L(...Sa)),ownership_enforcement:m(L("none","warn","strict")),create_mode_default:m(L("progressive","strict")),close_validation_default:m(L("off","warn","strict")),require_close_reason:m(N),parent_reference:m(L("warn","strict_error")),metadata_profile:m(L("core","strict","custom")),force_required_for_stale_lock:m(N),create_default_type:m(w),workflow_enforcement:m(L("off","warn","strict")),duplicate_detection_mode:m(L("off","advisory","strict")),duplicate_detection_threshold:m(M({min:0,max:1})),duplicate_detection_limit:m(M({int:!0,min:0,max:20}))})),vb=x({name:w,disabled:m(N),require_trusted:m(N),require_provenance:m(N),sandbox_profile:m(L("none","restricted","strict")),allowed_capabilities:m(k(w)),blocked_capabilities:m(k(w)),allowed_surfaces:m(k(w)),blocked_surfaces:m(k(w)),allowed_commands:m(k(w)),blocked_commands:m(k(w)),allowed_actions:m(k(w)),blocked_actions:m(k(w)),allowed_services:m(k(w)),blocked_services:m(k(w))}),Qi=L("block","warn"),kb=e=>typeof e=="string"?Qi(e):x({global:m(Qi),project:m(Qi)})(e),Tb=m(x({mode:m(L("off","warn","enforce")),trust_mode:m(L("off","warn","enforce")),pm_max_version_exceeded_mode:m(kb),require_provenance:m(N),trusted_extensions:m(k(w)),default_sandbox_profile:m(L("none","restricted","strict")),allowed_extensions:m(k(w)),blocked_extensions:m(k(w)),allowed_capabilities:m(k(w)),blocked_capabilities:m(k(w)),allowed_surfaces:m(k(w)),blocked_surfaces:m(k(w)),allowed_commands:m(k(w)),blocked_commands:m(k(w)),allowed_actions:m(k(w)),blocked_actions:m(k(w)),allowed_services:m(k(w)),blocked_services:m(k(w)),extension_overrides:m(k(vb))})),Lt=Zi(128),Sb=x({harness:Zi(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(k(Lt,64)),model_environment_keys:m(k(Lt,64)),session_environment_keys:m(k(Lt,64)),provenance_environment_keys:m(Gr(k(Lt,64))),provenance_resolvers:m(Gr(L("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(k(Lt,64)),argv_markers:m(k(Lt,64)),client_names:m(k(Lt,64))}),Ab=x({version:M({int:!0}),id_prefix:w,ids:m(x({token_length:m(M({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(x({probes_enabled:m(N),identity_vocabulary:m(x({version:M({int:!0,positive:!0}),aliases:Gr(Zi(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(Sb)})),mutation_guard:m(x({require_attributed_author:m(N),secret_guard:m(L("off","advise","block")),stale_in_progress_hours:m(M({int:!0,positive:!0}))})),item_format:m(L("toon","json_markdown")),locks:x({ttl_seconds:M({int:!0}),wait_ms:m(M({int:!0,min:0}))}),checkpoints:m(x({retention_days:m(M({int:!0,positive:!0}))})),output:x({default_format:L("toon","json")}),history:m(x({missing_stream:L("auto_create","strict_error"),compact_policy:m(x({enabled:m(N),max_entries:m(M({int:!0,positive:!0})),trigger:m(L("health_warn","auto"))}))})),validation:m(x({sprint_release_format:L("warn","strict_error"),parent_reference:m(L("warn","strict_error")),metadata_profile:m(L("core","strict","custom")),metadata_required_fields:m(k(w)),lifecycle_stale_blocker_reason_patterns:m(k(w)),lifecycle_closure_like_blocked_reason_patterns:m(k(w)),lifecycle_closure_like_resolution_patterns:m(k(w)),lifecycle_closure_like_actual_result_patterns:m(k(w)),estimate_defaults_by_type:m(Gr(M({int:!0,positive:!0})))})),governance:Eb,workflow:m(x({definition_of_done:k(w)})),testing:m(x({record_results_to_items:N})),telemetry:m(x({enabled:N,first_run_prompt_completed:m(N),capture_level:m(L("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(M({int:!0,positive:!0}))})),agent_guidance:m(x({prompt_completed:m(N),declined:m(N),declined_at:m(w),template_version:m(M({int:!0,positive:!0})),last_checked_files:m(k(w))})),item_types:m(x({definitions:k(_b)})),schema:wb,context:m(x({default_depth:m(L("brief","standard","deep")),activity_limit:m(M({int:!0,positive:!0})),stale_threshold_days:m(M({int:!0,positive:!0})),sections:m(x({hierarchy:m(N),activity:m(N),progress:m(N),recently_created:m(N),unparented:m(N),blockers:m(N),files:m(N),workload:m(N),staleness:m(N),tests:m(N)}))})),extensions:x({enabled:k(w),disabled:k(w),policy:Tb}),search:x({score_threshold:M(),hybrid_semantic_weight:m(M()),max_results:M({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(M()),embedding_batch_size:M({int:!0}),embedding_timeout_ms:m(M({int:!0})),scanner_max_batch_retries:M({int:!0}),provider:m(w),corpus_fields:m(k(w)),mutation_refresh_policy:m(L("cache_only","semantic_configured","semantic_auto")),query_expansion:m(x({enabled:m(N),provider:m(w)})),rerank:m(x({enabled:m(N),model:m(w),top_k:m(M({int:!0,positive:!0}))})),bm25:m(x({k1:m(M()),b:m(M())}))}),providers:x({openai:x({base_url:w,api_key:w,model:w}),ollama:x({base_url:w,model:w})}),vector_store:x({adapter:m(w),collection_name:m(w),qdrant:x({url:w,api_key:w}),lancedb:x({path:w})})});function yl(e){let t=Ab(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Nn from"node:path";import Ke from"node:fs/promises";import es from"node:path";import{randomUUID as xb}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 Cb(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 vl(e){try{let t=await Ke.readFile(e,"utf8");return await Ie({path:e,scope:"project"}),Cb(t)}catch(t){return X(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function ts(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function kl(e,t){await ge({path:e,scope:"project",op:t})}function Ib(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:F(),ttl_seconds:n}}async function Ob(e,t,n,r){await Ke.mkdir(es.dirname(e),{recursive:!0});let o=await Ke.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Ib(t,n,r),null,2)}
|
|
26
|
+
`,"utf8")}finally{await o.close()}await kl(e,"lock:create")}async function Tl(e,t){try{return await Ke.unlink(e),await kl(e,t),!0}catch{return!1}}function Sl(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 Rb(e){return e?.owner?` (owner ${e.owner})`:""}var Nb=25,Db=200,Lb=250,Pb=3,Mb=".stale-cleanup",Al="owner.json",Fb=1e4,$b=5*6e4;function bl(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 jb(e){let t=process.env.PM_LOCK_WAIT_MS,n=bl(t);if(n!==void 0)return n;let r=bl(e);return r!==void 0?r:0}function Ub(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function xl(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new y(`Item ${e} is locked${Rb(t)}${r}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:Lb}})}function zb(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 qb(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 Bb(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 Cl(e){try{return Bb(await Ke.readFile(es.join(e,Al),"utf8"))}catch{return null}}function Gb(e){try{return process.kill(e,0),!0}catch(t){return!ts(t,"ESRCH")}}async function ns(e){try{return await Ke.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function wl(e,t){let n=await Cl(e);n===null||n.token!==t||await ns(e)}async function El(e){try{await Ke.mkdir(e)}catch(n){return ts(n,"EEXIST"),null}let t={pid:process.pid,token:xb()};try{await Ke.writeFile(es.join(e,Al),`${JSON.stringify(t)}
|
|
27
|
+
`,"utf8")}catch{return await ns(e),null}return t}async function Vb(e){let t;try{let r=await Ke.stat(e);if(t=Date.now()-r.mtimeMs,t<=Fb)return!1}catch(r){return X(r)}let n=await Cl(e);return n!==null&&Gb(n.pid)&&t<=$b?!1:ns(e)}async function Hb(e,t){let n=`${e}${Mb}`,r=await El(n);if(r!==null)return async()=>wl(n,r.token);if(!await Vb(n))return null;let o=await El(n);return o===null?null:async()=>wl(n,o.token)}async function Wb(e){let t=await Hb(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await vl(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!Sl(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(qb(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=Pb)throw xl(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await Tl(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function Ne(e,t,n,r,o=!1,i=!0,s){let a=await $e("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=zb(a.result);if(p)return async()=>{await Promise.resolve(p()),await $e("lock_release",{pm_root:e,id:t,owner:r})}}let c=mc(e,t),l=jb(s),d=Date.now(),u=0,f=Nb;for(;;)try{return await Ob(c,t,r,n),async()=>{await Tl(c,"lock:release"),await $e("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!ts(p,"EEXIST"))throw new y(`Failed to acquire lock for ${t}: ${Be(p)}`,h.GENERIC_FAILURE);let _=await vl(c);if(Sl(_.info,n)){let b=await Wb({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 xl(t,_.info,l===0?0:g);await Ub(Math.min(f,l-g)),f=Math.min(f*2,Db)}}(function(){try{var e=typeof window<"u"?window:typeof 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 le="_workspace";function Vr(e){return Nn.join(e,"history",`${le}.jsonl`)}function Kb(e,t=e.length){let n=In();for(let r of e.slice(0,t))n=rn(n,r.patch).document;return On(n)}function Yb(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Xb(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 Jb(e,t){let n=Nn.resolve(t),r=Nn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Nn.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 rt(Vr(e),le),n=Ot(t);n.ok||Xb(n.errors);let r=Yb(t.length===0?Mo:Kb(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=Jb(e,Nn.resolve(e,c));if(l=await V(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d377bc4-c624-561c-9856-405c82099070")}catch{}})();var Qb={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Il=120;function os(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Rl(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var Zb=Rl(Qb),Ol=new WeakMap;function ew(e){let t=Ol.get(e);if(t)return t;let n=Rl(e);return Ol.set(e,n),n}function Nl(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Il;if(t){let o=ew(t).get(n);if(os(o))return Math.floor(o)}let r=Zb.get(n);return os(r)?Math.floor(r):Il}function Dl(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||!os(r)||(t[o]=Math.floor(r))}return t}import{stat as tw}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 Hr=new Map;function Ll(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function nw(e){try{let t=await tw(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function at(e){let t=Ll(e),n=await Promise.all(t.map(r=>nw(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Dn(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 Pl(e){return Hr.get(e)}function Wr(e,t){let n=Ll(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));Hr.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Pt(e){if(e){Hr.delete(e);return}Hr.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]="a434b9ea-4692-51c5-8761-0f1759fff394")}catch{}})();var $l=Symbol("pm.settings.persist_source"),ow=128,iw=new Set(["off","advisory","strict"]);function Ml(e){return structuredClone(Lo[e])}function sw(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:Z.governance.preset}function aw(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),iw.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 Mt(e){let t=e.governance??{},n=sw(t.preset),r=aw(t);if(n==="custom"){let s=Ml("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=Ml(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function jl(){return structuredClone(Z)}function cw(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:Z.search.mutation_refresh_policy}function lw(e){return typeof e=="boolean"?e:Z.search.query_expansion.enabled}function dw(e){return typeof e!="string"?Z.search.query_expansion.provider:e.trim()}function uw(e){return typeof e=="boolean"?e:Z.search.rerank.enabled}function fw(e){return typeof e!="string"?Z.search.rerank.model:e.trim()}function pw(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:Z.search.rerank.top_k}function mw(e){if(typeof e!="string")return Z.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,ow);return n.length>0?n:Z.vector_store.collection_name}function is(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function _w(e,t){let n=e.schema,r=is(n?.statuses),o=is(n?.fields),i=is(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Xr(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:Xr(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 Ul(e,t){Object.defineProperty(e,$l,{value:t,writable:!0,configurable:!0,enumerable:!1})}function gw(e){let t=e[$l];if(!(!t||typeof t!="object"))return t}function Yr(e){let t=structuredClone(e.settings),n=gw(e.settings);return n&&Ul(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function hw(e,t,n){let r=Ze(t);return[n,me(e,r.files.types,ce.types),me(e,r.files.statuses,ce.statuses),me(e,r.files.fields,ce.fields),me(e,r.files.workflows,ce.workflows)]}async function yw(e,t,n){let r=await at(t);Wr(e,{tracked_paths:t,signatures:r,value:Yr(n)})}async function bw(e,t,n){try{await yw(e,t,n)}catch{Pt(e)}}function Fl(e,t){return e.find(n=>n.path===t)}function ww(e,t,n){for(let r of n){let o=Fl(e,r),i=Fl(t,r);if(!o||!i||!Dn([o],[i]))return!1}return!0}async function ss(e,t,n,r,o){try{let i=await at(t);if(!ww(r,i,o)){Pt(e);return}Wr(e,{tracked_paths:t,signatures:i,value:Yr(n)})}catch{Pt(e)}}function Ln(e){return{settings:jl(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function Ew(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function vw(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function kw(e){let t=Z.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:vw(e?.last_checked_files??t.last_checked_files)}}function De(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Tw(e){return e==="off"||e==="warn"||e==="enforce"?e:Z.extensions.policy.mode}function Sw(e){return e==="off"||e==="warn"||e==="enforce"?e:Z.extensions.policy.trust_mode}function zl(e){return e==="none"||e==="restricted"||e==="strict"?e:Z.extensions.policy.default_sandbox_profile}function Aw(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=zl(e.sandbox_profile));let r=De(e.allowed_capabilities),o=De(e.blocked_capabilities),i=De(e.allowed_surfaces),s=De(e.blocked_surfaces),a=De(e.allowed_commands),c=De(e.blocked_commands),l=De(e.allowed_actions),d=De(e.blocked_actions),u=De(e.allowed_services),f=De(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 xw(e){let t=new Map;for(let n of e??[]){let r=Aw(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function as(e){return e==="block"||e==="warn"?e:void 0}function Cw(e){if(typeof e=="string")return as(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=as(e.global),n=as(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function ye(e,t){return De(e?.[t]??Z.extensions.policy[t])}function Iw(e){let t=Cw(e?.pm_max_version_exceeded_mode);return{mode:Tw(e?.mode),trust_mode:Sw(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ye(e,"trusted_extensions"),default_sandbox_profile:zl(e?.default_sandbox_profile),allowed_extensions:ye(e,"allowed_extensions"),blocked_extensions:ye(e,"blocked_extensions"),allowed_capabilities:ye(e,"allowed_capabilities"),blocked_capabilities:ye(e,"blocked_capabilities"),allowed_surfaces:ye(e,"allowed_surfaces"),blocked_surfaces:ye(e,"blocked_surfaces"),allowed_commands:ye(e,"allowed_commands"),blocked_commands:ye(e,"blocked_commands"),allowed_actions:ye(e,"allowed_actions"),blocked_actions:ye(e,"blocked_actions"),allowed_services:ye(e,"allowed_services"),blocked_services:ye(e,"blocked_services"),extension_overrides:xw(e?.extension_overrides??Z.extensions.policy.extension_overrides)}}function Ow(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 Kr(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Rw(e){return Array.isArray(e)?e:[]}function Nw(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Ow(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Kr(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Kr(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Kr(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Kr(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Dl(e.validation?.estimate_defaults_by_type)}}function Dw(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 Lw(e,t){return{...t.search,...e.search,mutation_refresh_policy:cw(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:lw(e.search?.query_expansion?.enabled),provider:dw(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:uw(e.search?.rerank?.enabled),model:fw(e.search?.rerank?.model),top_k:pw(e.search?.rerank?.top_k)}}}function Pw(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:mw(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function Mw(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function Fw(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 $w(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Xr(e){let t=(e??[]).map(r=>br(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 jw(e){let t=jl(),n=Mt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:Mw(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},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:Nw(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},telemetry:Dw(e,t),agent_guidance:kw(e.agent_guidance??t.agent_guidance),item_types:{definitions:Xr(e.item_types?.definitions)},schema:Ze(e.schema??t.schema),context:Fw(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:Iw(e.extensions.policy??t.extensions.policy)},search:Lw(e,t),providers:$w(e,t),vector_store:Pw(e,t)}}async function Pn(e){let t=U(e),n=[t];await Ie({path:t,scope:"project"});let r=Pl(e);if(r){let l=await at(r.tracked_paths);if(Dn(l,r.signatures))return Yr(r.value)}let o=await at([t]),i;try{i=await V(t)}catch{return Ln("settings_read_fs_error")}if(i===null){let l=Ln();return await ss(e,[t],l,o,[t]),l}let s=await at([t]);if(!Dn(o,s))return Pt(e),Pn(e);let a;try{a=JSON.parse(i)}catch{let l=Ln("settings_read_invalid_json");return await ss(e,[t],l,s,[t]),l}let c=yl(a);if(!c.success){let l=Ln("settings_read_invalid_schema");return await ss(e,[t],l,s,[t]),l}try{let l=jw(c.data),d=hw(e,l.schema,t);n=d;let u=await at(d),f=await za(e,l.schema),p=await qa(e,l.schema),_=await at(d),g={...l,item_types:{definitions:Xr([...l.item_types.definitions,...Rw(p.type_definitions_from_file)])},schema:p.schema};Ul(g,_w(c.data,g));let b={settings:g,metadata:{has_explicit_item_format:Ew(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(E=>`runtime_schema_bootstrap_created:${E}`),...p.warnings]};return f.created_paths.length===0?Dn(u,_)?Wr(e,{tracked_paths:d,signatures:_,value:Yr(b)}):Pt(e):Pt(e),b}catch{let l=Ln("settings_read_merge_failed");return await bw(e,n,l),l}}async function W(e){return(await Pn(e)).settings}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d79e3a4-6104-5855-837f-69a041b87b27")}catch{}})();var ls=["item","history","relationship","json"];function Bw(e){let t=e.trim().toLowerCase();if(ls.includes(t))return t;throw new y(`Unknown merge artifact "${e}". Supported values: ${ls.join(", ")}.`,h.USAGE)}function Gw(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 cs(e,t){try{return await Uw(e,"utf8")}catch{throw new y(`Cannot read merge ${t} file at ${e}.`,h.NOT_FOUND)}}async function Vw(e){let t=te(process.cwd(),e.path);return await D(U(t))?W(t):null}function Hw(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function Ww(e,t){let n=Bw(e.artifact),r=Gw(e.prefer),o=qw.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([cs(e.basePath,"base"),cs(e.oursPath,"ours"),cs(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=Vi(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=Hi(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 Vw(t),_=Wi(i,s,a,{format:Hw(e.itemPath??o,p),schema:p?.schema,extensionFieldNames:We(B()),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 p=Ki(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await zw(o,c,"utf8"),l!==void 0){let p=await hl(l);p!==null&&(u.receipt=Nt(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:F()}}import{readFile as Qr,realpath as ds,writeFile as Jw}from"node:fs/promises";import{execFile as Qw}from"node:child_process";import G from"node:path";import{promisify as Zw}from"node:util";import Kw 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 ql=["runtime/","search/","locks/","transactions/","checkpoints/"];function Bl(e){let t=e.replaceAll("\\","/");return Kw.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 Yw="PM_SOURCE_CONTEXT_ACCESS",Xw="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Gl(e){let t=e[Yw],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Xw]?.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]="5e1810a5-04b8-5929-8eee-7a63f1684860")}catch{}})();var us=Zw(Qw),Mn="# pm-cli:merge-drivers:start",fs="# pm-cli:merge-drivers:end",Ft="# pm-cli:merge-drivers:v2:start",Jr="# pm-cli:merge-drivers:v2:end",eE="merge-fence";function Vl(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Kl(){let e=Yt(import.meta.url,["../../.."]);return`${Vl(process.execPath)} ${Vl(G.join(e,"dist","cli.js"))}`}var Yl=[{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 Xl(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=Gl(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=te(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:G.resolve(r),workspace_start:G.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?te(e.cwd,".agents/pm"):te(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function sn(e){try{let{stdout:t}=await us("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ds(t.trim())}catch{return null}}async function Jl(e){let t=await sn(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function ps(e,t){return G.relative(e,t).replaceAll("\\","/")}function je(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Hl(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 tE(e,t){let n=Hl(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=Hl(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(G.basename(n.value))||G.basename(r.value)!=="cli.js"||G.basename(G.dirname(r.value))!=="dist"||!await D(n.value)||!await D(r.value))return!1;try{let o=G.dirname(G.dirname(r.value)),i=JSON.parse(await Qr(G.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 Zr(e,t){let n=e.length>0?`${e}/`:"",r=[`${je(`${n}**/*.toon`)} merge=pm-item-toon`,`${je(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${je(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${je(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${je(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${je(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${je(`${n}settings.json`)} merge=pm-json`),r.push(`${je(`${n}**/*.json`)} merge=pm-json`),r.push(`${je(`${n}extensions/**`)} -merge`),r.push(`${je(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Wl(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 Ql(e,t,n){let r=G.join(e,".gitattributes"),o="";try{o=await Qr(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&X(l)))throw l}let i=[Ft,...t,Jr].join(`
|
|
28
|
+
`),a=Wl(Wl(o,Ft,Jr),Mn,fs).trimEnd(),c=`${a.length>0?`${a}
|
|
29
29
|
|
|
30
30
|
`:""}${i}
|
|
31
|
-
`;return c===o?{path:r,changed:!1}:(n||await
|
|
32
|
-
`).map(
|
|
31
|
+
`;return c===o?{path:r,changed:!1}:(n||await Jw(r,c,"utf8"),{path:r,changed:!0})}function eo(e){let t=oe(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ms(e,t){let n=G.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let C=G.join(i,".gitattributes");try{let O=await Qr(C,"utf8");if(O.includes(Ft)||O.includes(Mn)){r=i,o=O;break}}catch{}let A=G.dirname(i);if(A===i)break;i=A}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=G.join(r,".gitattributes"),a=o.includes(Ft),c=a?Ft:Mn,l=a?Jr:fs,d=o.indexOf(c),u=o.indexOf(l),f=u>d?o.slice(d+c.length,u).split(`
|
|
32
|
+
`).map(v=>v.trim()).filter(v=>v.length>0):[],p=Zr(ps(r,n),t),_=new Set(f),g=new Set(p),b=p.filter(v=>!_.has(v)),E=f.filter(v=>!g.has(v));return{status:b.length>0||E.length>0?"drift":"ok",path:s,missing_patterns:b,stale_patterns:E,schema_scope:"project"}}async function _s(e){let t=Kl(),n=[],r=[];for(let o of Yl){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 us("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await tE(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 nE(e){let t;try{t=await Jl(G.resolve(e))}catch{return{status:"no_git"}}let n=ps(t,G.resolve(e)),r=await W(e),o=Oe(void 0,r.author_default),i=await Ne(e,eE,r.locks.ttl_seconds,o,!1,Mt(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=G.join(t,".gitattributes"),a;try{a=await Qr(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&X(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Ft)&&!a.includes(Mn))return{status:"not_installed",path:s};let c=await W(e),l=eo(c),d=await Ql(t,Zr(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function rE(e,t){let n=Xl({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;if(!await D(U(r)))throw new y(`Tracker is not initialized at ${r}. Run pm init first.`,h.NOT_FOUND);let o=await Jl(n.workspace_start);return oE({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function oE(e){let t=G.resolve(e.pmRoot),n=G.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([ds(t),ds(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=ps(i,o);if(Bl(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 W(o),c=eo(a),l=Zr(s,c),d=[],u=Kl();for(let p of Yl)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 us("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 Ql(i,l,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:f.path,changed:f.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:F()}}import $d 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 Zl(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Fn(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?Zl(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Zl(t):"root"}import mv from"node:fs/promises";import ut from"node:fs/promises";import cn from"node:path";import 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]="58fd6fef-9c13-5c6a-9110-b760461896aa")}catch{}})();function aE(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function cE(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 lE(e,t){return await wt(sE.dirname(e)),await(await iE.open(e,"a")).close(),ge({path:e,scope:"project",op:`${t}:history:auto_create`})}async function gs(e){return ed({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function ed(e){let t=aE(e.itemIds),n=[],r=[];for(let o of t){let i=Fe(e.pmRoot,o);if(!await D(i)){if(e.settings.history.missing_stream==="strict_error")throw cE(o,e.commandLabel);r.push(...await lE(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]="50a277b9-d530-5aa0-8bd0-8eb0d36911e5")}catch{}})();function dE(e){let t=(e??"").trim().toLowerCase();return t?t.endsWith("-")?t:`${t}-`:"pm-"}function an(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function ct(e,t){let n=dE(t),r=an(e);return r.startsWith(n)?r:`${n}${r}`}import ie from"node:fs/promises";import j from"node:path";import{createHash as yE,randomUUID as ud}from"node:crypto";import $t from"node:fs/promises";import td from"node:path";import{randomUUID as uE}from"node:crypto";import{createRequire as fE}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 pE="metadata-query-index.sqlite",nd="4";function mE(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var to;function _E(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?mE(t):null}function rd(){return to!==void 0||(to=_E(process.versions.node,fE(import.meta.url))),to}function hs(e){return td.join(e,"runtime",pE)}function gE(e){e.exec(`
|
|
33
33
|
PRAGMA foreign_keys = ON;
|
|
34
34
|
PRAGMA journal_mode = OFF;
|
|
35
35
|
PRAGMA synchronous = OFF;
|
|
@@ -84,7 +84,7 @@ ${i}
|
|
|
84
84
|
tags,
|
|
85
85
|
tokenize = 'unicode61'
|
|
86
86
|
);
|
|
87
|
-
`)}function
|
|
87
|
+
`)}function no(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function od(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
|
|
88
88
|
id, relative_path, metadata_json, status, type, priority,
|
|
89
89
|
updated_at, created_at, parent, assignee, sprint, release
|
|
90
90
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -99,13 +99,13 @@ ${i}
|
|
|
99
99
|
parent = excluded.parent,
|
|
100
100
|
assignee = excluded.assignee,
|
|
101
101
|
sprint = excluded.sprint,
|
|
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 Ql(e){let t=ps(e.pmRoot),n=Xl();if(!n){await Ft.rm(t,{force:!0});return}await Ft.mkdir(Kl.dirname(t),{recursive:!0});let r=`${t}.${Hw()}.tmp`,o;try{o=new n(r),Jw(o),o.exec("BEGIN IMMEDIATE"),Qr(o,"version",Yl),Qr(o,"context_fingerprint",e.contextFingerprint),Qr(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Jl(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Ft.rm(t,{force:!0}),await Ft.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Ft.rm(r,{force:!0})]),i}}function Qw(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Zl(e){let t=ps(e.pmRoot),n;try{await Ft.access(t);let r=Xl();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Qw(n);if(o.version!==Yl||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&&Jl(n,e.row),Qr(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function Zr(e){await Ft.rm(ps(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 Ue=8,id=500,ev="metadata-derived-index",tv="metadata-cache.json",nv="metadata-cache-bodies.json",rv="metadata-cache-collections.json",ov="metadata-cache-delta.json",iv="metadata-cache-manifest.json",ed=4,sv=["comments","notes","learnings","files","tests","test_runs","docs"];function sd(){return We(B())}function to(e){let t={...e},n={};for(let r of sv)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function ad(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function cd(e,t,n,r){let o=Zw("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 no(e){return j.join(e,"runtime",tv)}function ro(e){return j.join(e,"runtime",nv)}function oo(e){return j.join(e,"runtime",rv)}function gs(e){return j.join(e,"runtime",ov)}function hs(e){return j.join(e,"runtime",iv)}function io(e,t){let n=j.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var av=24,ke=new Map,so=new WeakMap;function ys(e){return so.get(e)??e.source_cursor}function cv(e,t){let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){so.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 lv(e,t){if(!e)return;let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){so.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 dv(e,t){if(!e)return;let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){so.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 uv(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(cv(e,r),lv(t,r),dv(n,r))}function ms(e,t){ke.size>=av&&!ke.has(e)&&Bt(ke),ke.set(e,t)}async function lt(e,t){let n;try{n=await ie.stat(e)}catch{return ke.delete(e),null}let r=ke.get(e);if(r&&Fn(r.signature,n.mtimeMs,n.ctimeMs,n.size))return ke.delete(e),ke.set(e,r),r.envelope;let o;try{o=t(await ie.readFile(e,"utf8"))}catch{o=null}return ms(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function fv(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==Ue||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=no(e),i=await lt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await lt(io(o,t),r);return s===null&&Un(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function pv(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ue||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=ro(e),o=await lt(r,n);return t&&o?.context_fingerprint!==t?await lt(io(r,t),n):o}async function mv(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ue||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=oo(e),o=await lt(r,n);return t&&o?.context_fingerprint!==t?await lt(io(r,t),n):o}async function ld(e){let t=gs(e),n=await lt(t,r=>{let o=JSON.parse(r);return o.version!==Ue||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 ie.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function dd(e){let t=hs(e),n=await lt(t,r=>{let o=JSON.parse(r);return o.version!==Ue||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 ie.stat(t),await $n(e)}catch{}return null}async function jn(e,t){await ie.mkdir(j.dirname(e),{recursive:!0}),await L(e,JSON.stringify(t));try{let r=await ie.stat(e);ms(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{ke.delete(e)}let n=j.dirname(j.dirname(e));if(e===no(n)||e===ro(n)||e===oo(n)){let r=io(e,t.context_fingerprint);await L(r,JSON.stringify(t));try{let c=await ie.stat(r);ms(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{ke.delete(r)}let o=j.dirname(e),i=j.extname(e),s=j.basename(e,i),a=(await ie.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==j.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>j.join(o,c.name));if(a.length>ed){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await ie.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-ed)))await ie.rm(l.path,{force:!0}),ke.delete(l.path)}}}function _v(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ud(e,t,n){return e===void 0||_v(e,t,n)}function Un(e,t){e&&!e.includes(t)&&e.push(t)}function Fn(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function gv(e,t,n){let r=j.join(e,t);try{let o=await ie.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!X(o)&&Un(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function hv(e,t){try{let n=await ie.stat(j.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 _s(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await hv(e,n))))}function eo(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&&Fn(o,r.mtime_ms,r.ctime_ms,r.size)})}function yv(e){return Yt.some(t=>e.toLowerCase().endsWith(t))}function bv(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function wv(e,t,n){if(n)for(let r of await Ie({path:e,scope:"project"}))Un(t,r)}function td(e,t,n,r){if(e)return t&&n?n.collections:r}async function vv(e,t,n){let r=await ie.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=yr(e);await wv(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Fn(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Fn(d,o,i,s),f=n.previousCollections[t],m=!n.forceSourceRead&&f!==void 0&&Fn(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:td(n.includeCollections,m,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let h=await ie.readFile(e,"utf8"),b=Me(h,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:E=>Un(n.warnings,E)}),v=to(b.metadata);return bv(n.state.misses,n.includeBody,n.includeCollections,l,u,m),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:v.light,heavyMetadata:td(n.includeCollections,m,f,v.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function Ev(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?ad(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};ud(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function kv(e,t,n,r){try{let o=await vv(t,n,r);Ev(t,n,r,o)}catch{Un(r.warnings,`item_list_item_read_failed:${e}/${j.basename(t)}`)}}function Tv(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function Sv(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function Av(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function xv(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function Cv(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!yv(s))continue;let a=j.join(o,s),c=j.relative(t.pmRoot,a);n.push(kv(r,a,c,t))}return n}async function Iv(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!eo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await jn(no(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await jn(hs(e.pmRoot),{version:Ue,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:j.relative(e.pmRoot,r.item_path),metadata:to(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Ql({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Zr(e.pmRoot)}catch{}}async function Ov(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 jn(ro(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function Rv(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 jn(oo(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function bs(e,t,n={}){let r=await dd(e);return n.required!==!0&&(r===null||r.entry_count<id)?async()=>{}:Ne(e,ev,30,t,!1,!1,3e3)}function nd(e,t){let n=j.relative(e,t);return n===""||n===".."||n.startsWith(`..${j.sep}`)||j.isAbsolute(n)?null:n}async function $n(e){await Promise.all([no(e),ro(e),oo(e),gs(e),hs(e)].map(async t=>{await ie.rm(t,{force:!0}),ke.delete(t)})),await Zr(e)}async function Nv(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await ie.stat(e.mutation.itemPath),n=to(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 Dv(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function ws(e){let t=nd(e.pmRoot,e.itemPath),n=e.previousItemPath?nd(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await $n(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=cd(e.preferredFormat,e.typeToFolder,e.schema,sd()),o=await dd(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await ld(e.pmRoot);if(s.invalid)return await $n(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=Dv(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 Nv({mutation:e});let l=od();return await jn(gs(e.pmRoot),{version:Ue,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await _s(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Zl({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:to(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Zr(e.pmRoot),[]}catch{return await $n(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function Lv(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function rd(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function Pv(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function Mv(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=yr(n);if(!o)continue;let i=e.includeCollections?ad(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ud(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:j.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function Fv(e){return e.forceSourceScan||Er()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!eo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||rd(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||rd(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&Pv(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function ao(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=sd(),l=cd(t,n,o,c),d=await ld(e);d.invalid&&await $n(e);let u=await fv(e,l,i.cacheDiagnostics),f=s?await pv(e,l):null,m=a?await mv(e,l):null;uv(u,f,m,d.envelope);let _=Tv(u,l),h=Sv(f,l),b=Av(m,l),v=[...new Set(Object.values(n))],E=await _s(e,v),I=Object.keys(_),A=Math.max(1,Math.floor(i.derivedIndexMinimumItems??id));if(Fv({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:m,directorySignatures:E,entryKeys:I,minimumIndexedItems:A,includeBody:s,includeCollections:a,previousBodies:h,previousCollections:b}))return Mv({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:h,previousCollections:b});let O=await Promise.all(v.map(K=>gv(e,K,r))),Q=Er(),$=xv(),fe={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:Q,previousEntries:_,previousBodies:h,previousCollections:b,state:$};await Promise.all(Cv(O,fe));let z=await _s(e,v),pe=eo(E,z)?z:{},C=$.misses.metadata||Object.keys(_).length!==Object.keys($.newEntries).length||!eo(u?.directory_signatures,pe)||u===null?od():u.source_cursor;return await Iv({pmRoot:e,contextFingerprint:l,sourceCursor:C,existingCache:u,previousEntries:_,directorySignatures:pe,state:$,minimumIndexedItems:A}),s&&await Ov({pmRoot:e,contextFingerprint:l,sourceCursor:C,existingBodyCache:f,previousBodies:h,state:$}),a&&await Rv({pmRoot:e,contextFingerprint:l,sourceCursor:C,existingCollectionsCache:m,previousCollections:b,state:$}),Lv($)}async function fd(e,t,n,r,o){return(await ao(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]="d24d61bf-7db8-5f35-8dbc-5ef93ec8220b")}catch{}})();async function $v(e){try{return await ut.access(e),!0}catch{return!1}}function dt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function jv(e,t){e&&(e.includes(t)||e.push(t))}function Uv(e){return e??We(B())}function zv(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}function co(e){return new y(`Tracker root is not a directory at ${e}.`,g.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",nextSteps:["Pass the tracker directory itself, usually <workspace>/.agents/pm."]})}function vs(e){return new y(`Tracker root is not readable at ${e}.`,g.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",nextSteps:["Grant read and directory-search permission to the tracker root, then retry the SDK read."]})}async function qv(e){let t=an.parse(an.resolve(e)).root,n=an.dirname(an.resolve(e));for(;n!==t;){let r;try{r=await ut.stat(n)}catch(o){if(dt(o,"ENOTDIR"))throw co(e);if(!dt(o,"ENOENT"))throw o;n=an.dirname(n);continue}if(!r.isDirectory())throw co(e);break}}async function pd(e){let t;try{t=await ut.stat(e)}catch(n){throw dt(n,"ENOENT")?(await qv(e),new y(`Tracker root does not exist at ${e}.`,g.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",nextSteps:["Confirm the tracker root path and retry the SDK read.","Initialize a tracker before enumerating its item metadata."]})):dt(n,"ENOTDIR")?co(e):dt(n,"EACCES")||dt(n,"EPERM")?vs(e):n}if(!t.isDirectory())throw co(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw vs(e);try{await(await ut.opendir(e)).close()}catch(n){throw dt(n,"EACCES")||dt(n,"EPERM")?vs(e):n}}async function Le(e,t,n="pm-",r,o=we){let i=ct(t,n),s=sn(t),a=i===s?[i]:[i,s],c=Object.entries(o),l=zv(r);for(let d of a)for(let[u]of c)for(let f of l){let m=Xt(e,u,d,f,o);if(await $v(m))return{id:d,type:u,itemPath:m,item_format:f}}return null}async function Te(e,t={}){let n=await ut.readFile(e.itemPath,"utf8");await Ie({path:e.itemPath,scope:"project"});let r=Me(n,{format:e.item_format,schema:t.schema,extensionFieldNames:Uv(t.extensionFieldNames),onWarning:o=>jv(t.warnings,o)});return{raw:n,document:r}}async function zn(e,t,n=we,r,o){return await pd(e),(await fd(e,t,n,r,o)).map(s=>s.metadata)}async function lo(e,t,n=we,r,o,i={}){return await pd(e),(await ao(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function md(e){return{async get(t){let n=await Le(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Te(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>zn(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Bv(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await ut.readdir(an.join(e,o));for(let s of i)for(let a of Yt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function Gv(e,t,n,r){let o=ct(t,n),i=await Bv(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Tt(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function _d(e,t,n,r){let o=await Gv(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`,g.NOT_FOUND,{nextSteps:i})}function Vv(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 Hv(e){let t=e.typeToFolder??oe(e.settings,B()).type_to_folder,n=await Le(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await _d(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await Ne(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 Te(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=Ei(e.author),d=Pt(e.settings);if(a&&c!==l&&!e.force&&!Vv(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new y(`Item ${n.id} is assigned to ${a}. Use --force to override.`,g.CONFLICT);d.ownership_enforcement==="warn"&&o.push(`ownership_warning:assignee_conflict:${n.id}:${a}`)}return{typeToFolder:t,located:n,originalRaw:i,document:s,warnings:o,releaseLock:r}}catch(o){throw await r(),o}}function Wv(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 Kv(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await L(e.originalItemPath,e.originalRaw),await ut.rm(e.effectiveTargetItemPath,{force:!0});return}await L(e.originalItemPath,e.originalRaw)}}async function uo(e){let t=await Hv({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=_e(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=_e(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??[]]};l.metadata.updated_at=F();let u=_e(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await li({pm_root:e.pmRoot,operation:e.op,before:c,after:u,changed_fields:d.changedFields,sdk:md({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let f=await fs({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),m="toon",_=Et(u,{format:m,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),h=Xt(e.pmRoot,u.metadata.type,r.id,m,n),b=Fe(e.pmRoot,r.id),v=await $e("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:h,history_path:b,item_format:m,before:c,after:u,contents:_}),{effectiveTargetItemPath:E,effectiveSerializedAfter:I,skipItemWrite:A}=Wv(v,h,_),O=await bs(e.pmRoot,e.author),Q=[];try{A||await L(E,I),!A&&E!==r.itemPath&&await ut.rm(r.itemPath);let fe=xn({nowIso:u.metadata.updated_at,author:e.author,op:e.op,before:c,after:u,message:e.message});try{await Pr(b,fe)}catch(z){throw await Kv({skipItemWrite:A,effectiveTargetItemPath:E,originalItemPath:r.itemPath,originalRaw:o}),z}A||(Q=await ws({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:E,previousItemPath:r.itemPath,document:u}))}finally{await O()}let $=[...await ge({path:E,scope:"project",op:e.op,item_id:u.metadata.id,item_type:u.metadata.type,before:c,after:u,changed_fields:d.changedFields}),...await ge({path:b,scope:"project",op:`${e.op}:history`,item_id:u.metadata.id,item_type:u.metadata.type,before:c,after:u,changed_fields:d.changedFields})];return ci({id:u.metadata.id,op:e.op,item_type:u.metadata.type,previous_status:c.metadata.status,status:u.metadata.status,previous:vr(c.metadata,d.changedFields),current:vr(u.metadata,d.changedFields),changed_fields:d.changedFields}),{item:u.metadata,body:u.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...f.warnings,...v.warnings,...Q,...$]}}finally{await 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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function Xv(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Pt(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Jv(e){let t=await V(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await Le(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await Te(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}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function gd(e){let t=e.writeHistoryRaw??L;try{await t(e.historyPath,e.nextHistoryRaw),await He(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Yv.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await He(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function Es(e){let t=[...Xv({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await Ne(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 Jv({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 cn from"node:fs/promises";import{createHash as Qv}from"node:crypto";import yd 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 bd=4,Zv="history-drift-cache.json";function wd(e){return yd.join(e,"runtime",Zv)}async function eE(e){try{let t=await cn.readFile(wd(e),"utf8"),n=JSON.parse(t);return n.version!==bd||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function tE(e,t,n,r,o){let i=zr(e),s;try{s=await cn.stat(i)}catch(l){return X(l)||o.unreadableStreams.push(le),!1}let a=o.missingStreams.length,c=await Ed({itemId:le,historyPath:i,stat:s,cached:t[le],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.chainOk||o.chainMismatches.push(le),n[le]={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 vd(e){return Qv("sha256").update(e).digest("hex")}async function nE(e){let t=await cn.readFile(e,"utf8");return vd(t)}async function rE(e){let t=await cn.readFile(e,"utf8"),n=vd(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=Ct(r);return{latestAfterHash:o,chainOk:i.ok,contentHash:n,itemHashVersion:i.item_hash_version??Re}}function oE(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function hd(e,t,n){try{let r=await rE(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Ed(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(oE(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await hd(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await nE(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??Re},cacheDirty:!1}:{verification:await hd(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function iE(e,t,n,r){let o=Fe(e,t.id),i;try{i=await cn.stat(o)}catch(d){return(X(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Ed({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 An({metadata:c,body:a},s.verification.itemHashVersion)!==s.verification.latestAfterHash&&r.hashMismatches.push(t.id),s.cacheDirty}async function sE(e,t){if(!(t.unreadableStreams.includes(le)||t.chainMismatches.includes(le)))try{let n=await Zi(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(le)}}async function fo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await eE(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await iE(e,f,l,r)&&(a=!0);let d=await tE(e,i,s,c,r);if(a||=d,await sE(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=wd(e);try{await cn.mkdir(yd.dirname(f),{recursive:!0}),await L(f,JSON.stringify({version:bd,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?[le]:[]])].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]="cd2a27ec-0f12-591d-ab34-529ddda05063")}catch{}})();async function kd(e,t,n,r){let o=await Le(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Fe(e,o.id),located:o};let i=ct(t,n.id_prefix),s=sn(t),a=i===s?[i]:[i,s];for(let c of a){let l=Fe(e,c);if(await N(l))return{id:c,historyPath:l,located:null}}throw new y(`Item ${t} not found`,g.NOT_FOUND)}import Td from"node:fs/promises";import Sd 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 aE=[{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 qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e){return aE.find(t=>t.matches(e))?.kind}function xd(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=qn(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=qn(u)?Ad(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}`,h=t.get(_)??{harness:m,dimension:d,kind:f,count:0};h.count+=1,t.set(_,h)}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 Cd(e){let t=[];for(let n of await cE(e))try{let r=await Td.readFile(Sd.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
103
|
-
`)){if(o.trim().length===0)continue;let i=lE(o);if(i===null||!qn(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>qn(a)&&Ad(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function cE(e){try{return(await Td.readdir(Sd.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function lE(e){try{let t=JSON.parse(e);return qn(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]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function Id(e,t){return t==="body"?e.body:e.metadata[t]}function ks(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)&&ks(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)&&ks(o,n[r]))}function Od(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 On(i.patch))s.add(Mn(c.path)),c.from&&s.add(Mn(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 dE(e,t,n){let r=Rd.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(Mn(_.path));let i=new Set([...o].filter(_=>ks(Id(t,_),Id(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=Od(e,s),c=Od(e,i),l=[...o].sort((_,h)=>_.localeCompare(h)),d=[...s].sort((_,h)=>_.localeCompare(h)),u=[...i].sort((_,h)=>_.localeCompare(h)),f=[...new Set(a.map(_=>_.author))].sort((_,h)=>_.localeCompare(h)),m=[...new Set(c.map(_=>_.author))].sort((_,h)=>_.localeCompare(h));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 uE(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Te(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=Di(i.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:Ee(s,r)===a,currentItemRawBeforeLock:i.raw,loadedItem:i}}function fE(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 pE(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:F(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Rd.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ee(e.finalReplay,e.itemHashVersion),after_hash:Ee(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 mE(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 _E(e){return Es({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})=>gd({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ge({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Ts(e,t,n){let r=te(process.cwd(),n.path);if(!await N(U(r)))throw new y(`Tracker is not initialized at ${r}. Run pm init first.`,g.NOT_FOUND);let o=await W(r),i=oe(o,B()),s=await kd(r,e,o,i.type_to_folder);if(!await N(s.historyPath))throw new y(`No history stream exists for ${s.id}.`,g.NOT_FOUND);let a=await V(s.historyPath),c=await rt(s.historyPath,s.id);if(c.length===0)throw new y(`No history entries exist for ${s.id}; nothing to repair.`,g.USAGE);let l=It(c),d=Ct(c),u=t.normalizeProvenance?xd(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=Li(u.entries),m=new Set(u.entries.map(q=>q.item_hash_version).filter(q=>q!==void 0)),_=Mr(u.entries,f),h=await uE(s,o,c,f),b=_.finalDocument,v=h.currentItemReplay!==null&&Ee(b,f)!==Ee(h.currentItemReplay,f),E=v&&h.currentItemReplay?dE(_.entries,b,h.currentItemReplay):void 0,I=[_.entriesRehashed>0,_.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),A=Oe(t.author,o.author_default),O=!!t.dryRun,Q=fE({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:$,auditEntryAdded:fe}=pE({reanchorEntries:_.entries,changed:I,reconcileNeeded:v,currentItemReplay:h.currentItemReplay,finalReplay:b,author:A,message:Q,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...t.auditContext,provenance_normalization:u.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),z=It($);if(!z.ok)throw new y(`history-repair produced an invalid rewritten chain (${z.errors.join(", ")}).`,g.GENERIC_FAILURE);let pe=mE(I,_.skippedOps,E);return I&&!O&&pe.push(...await _E({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:h.currentItemRawBeforeLock,author:A,force:t.force,loadedItem:h.loadedItem,historyPath:s.historyPath,rewrittenEntries:$})),{id:s.id,dry_run:O,changed:I,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!l.ok,entries_rehashed:_.entriesRehashed,entries_patch_repaired:_.entriesPatchRepaired,converted_replace_to_add:_.convertedReplaceToAdd,skipped_ops:_.skippedOps,reconciled_with_item:v,audit_entry_added:fe,verify_ok:z.ok,verify_errors:z.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:h.currentItemPath!==null,path:h.currentItemPath,matched_chain_before:h.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...E?{reconciliation:E}:{},warnings:[...new Set(pe)].sort((q,C)=>q.localeCompare(C)),generated_at:F()}}async function Nd(e,t){let n=te(process.cwd(),t.path);if(!await N(U(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let r=await W(n),o=oe(r,B()),i=[],s=await lo(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await fo(n,s),c=e.normalizeProvenance?await Cd(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 Ts(m,{...e,auditContext:e.auditContextById?.[m],auditContextById:void 0},t),h=_.changed?"repaired":"skipped_clean";f[h]+=1,u.push(..._.warnings.map(b=>`${m}:${b}`)),d.push({id:m,outcome:h,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 Ii(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:F()}}import fa from"node:fs/promises";import{realpathSync as hS}from"node:fs";import{execFile as yS}from"node:child_process";import ue from"node:path";import{promisify as bS}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 gE=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 hE(e){if(typeof e!="string")return;let t=e.trim();for(let n of gE)if(t===n.code||t.startsWith(`${n.code}:`))return n}function yE(e){let t={};for(let n of e){let r=hE(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Dd(e){return Object.values(yE(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 bE=["metadata","resolution"],Ss=["metadata","resolution","estimates","lifecycle"],wE="completed";function As(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ld(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Pd(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Ld(n.close_reason)??wE;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${As(r)}`,gate:"resolution"})}return t}function Md(e){let t=[];for(let n of e){let r=Ld(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 ${As(r)}`,gate:"metadata"})}return t}function Fd(e,t){return e.map(n=>{let r=Sl(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 $d(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 jd(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 ${As(n.path)}`})}return t}function Ud(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: ${Ss.join(", ")}.`,g.USAGE);return new Set(bE)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(Ss.includes(o)){n.add(o);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Ss.join(", ")}.`,g.USAGE)}return n}function zd(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 Bn(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 vE=/^([A-Z][A-Z0-9]*-\d+)\b/;function EE(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=vE.exec(t);return n?n[1]:null}function qd(e){return typeof e=="string"&&e.trim().length>0}function Bd(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||qd(r.duplicate_of))continue;let o=EE(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:qd(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 Gd(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 Vd=3;function Hd(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Wd(e,t,n=Vd){let r=Number.isFinite(n)&&n>=1?Math.floor(n):Vd,o=new Map;for(let i of t){let s=Hd(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(Hd(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 Kd(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 kE=/^[a-z][a-z0-9+.-]+:\/\//i;function Gn(e){return kE.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 TE(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Yd(e){return`${e.item_id} ${e.link_kind}`}function Xd(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=TE(o.classification,r.classification),o.owners.set(Yd(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Yd(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 SE(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Jd(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="${SE(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 AE="global",xE="external";function Qd(e){let t=e?.trim().toLowerCase();return t===AE||t===xE}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fc5da1-b7d1-5b3c-8033-cecccc7861c3")}catch{}})();function CE(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function Zd(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=CE(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;Qd(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 ln from"node:fs/promises";import dn 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 IE(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await ln.readdir(dn.join(e,o))}catch{return}for(let s of i)for(let a of Yt)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 OE(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Ce(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 xs(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 RE(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await ln.readdir(dn.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 ln.readFile(dn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:xs("history stream",s)});continue}OE({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function eu(e){let t=Ce(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 NE(e){let t=[],n=0,r=null;try{r=await V(U(e))}catch(i){n+=1,t.push({path:"settings.json",detail:xs("configuration file",i)})}if(r!==null){n+=1;let i=eu(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await ln.readdir(dn.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 ln.readFile(dn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:xs("configuration file",c)});continue}let a=eu(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function tu(e,t,n,r={}){let o=await IE(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=dn.join(e,u.relativePath);return Me(await ln.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 RE(e,i),d=await NE(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 DE}from"node:child_process";import{realpath as LE}from"node:fs/promises";import nu from"node:path";import{promisify as PE}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 ME=PE(DE),FE=32*1024*1024,$E=1e4,jE=["search/eval-queries.json"];function Cs(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function UE(e){return`'${e.replaceAll("'","'\\''")}'`}async function zE(e,t=LE){return t(e).catch(()=>nu.resolve(e))}async function ru(e){let t=await on(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 zE(e),r=Cs(nu.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=Pl.map(i=>`${r}/${Cs(i)}`);try{let{stdout:i}=await ME("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:FE,windowsHide:!0,timeout:$E}),s=new Set(jE.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(Cs(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=>UE(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import ia from"node:fs/promises";import sa from"node:path";import{Option as eG}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]="7426082f-94a6-5b4e-9748-d3faab2fe1d4")}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]="d5003dd5-f208-5734-9711-dff935d8c851")}catch{}})();var un="-",ou=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 Is(e){return e.replace(/\r\n/g,`
|
|
104
|
-
`)}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 id(e){let t=hs(e.pmRoot),n=rd();if(!n){await $t.rm(t,{force:!0});return}await $t.mkdir(td.dirname(t),{recursive:!0});let r=`${t}.${uE()}.tmp`,o;try{o=new n(r),gE(o),o.exec("BEGIN IMMEDIATE"),no(o,"version",nd),no(o,"context_fingerprint",e.contextFingerprint),no(o,"source_cursor",e.sourceCursor);for(let i of e.rows)od(o,i);o.exec("COMMIT"),o.close(),o=void 0,await $t.rm(t,{force:!0}),await $t.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([$t.rm(r,{force:!0})]),i}}function hE(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function sd(e){let t=hs(e.pmRoot),n;try{await $t.access(t);let r=rd();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=hE(n);if(o.version!==nd||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&&od(n,e.row),no(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 $t.rm(hs(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 Ue=8,fd=500,bE="metadata-derived-index",wE="metadata-cache.json",EE="metadata-cache-bodies.json",vE="metadata-cache-collections.json",kE="metadata-cache-delta.json",TE="metadata-cache-manifest.json",ad=4,SE=["comments","notes","learnings","files","tests","test_runs","docs"];function pd(){return We(B())}function io(e){let t={...e},n={};for(let r of SE)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function md(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function _d(e,t,n,r){let o=yE("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 so(e){return j.join(e,"runtime",wE)}function ao(e){return j.join(e,"runtime",EE)}function co(e){return j.join(e,"runtime",vE)}function ws(e){return j.join(e,"runtime",kE)}function Es(e){return j.join(e,"runtime",TE)}function lo(e,t){let n=j.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var AE=24,ke=new Map,uo=new WeakMap;function vs(e){return uo.get(e)??e.source_cursor}function xE(e,t){let n=vs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){uo.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 CE(e,t){if(!e)return;let n=vs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){uo.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 IE(e,t){if(!e)return;let n=vs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){uo.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 OE(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(xE(e,r),CE(t,r),IE(n,r))}function ys(e,t){ke.size>=AE&&!ke.has(e)&&Bt(ke),ke.set(e,t)}async function lt(e,t){let n;try{n=await ie.stat(e)}catch{return ke.delete(e),null}let r=ke.get(e);if(r&&$n(r.signature,n.mtimeMs,n.ctimeMs,n.size))return ke.delete(e),ke.set(e,r),r.envelope;let o;try{o=t(await ie.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 RE(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==Ue||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=so(e),i=await lt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await lt(lo(o,t),r);return s===null&&zn(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function NE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ue||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=ao(e),o=await lt(r,n);return t&&o?.context_fingerprint!==t?await lt(lo(r,t),n):o}async function DE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ue||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=co(e),o=await lt(r,n);return t&&o?.context_fingerprint!==t?await lt(lo(r,t),n):o}async function gd(e){let t=ws(e),n=await lt(t,r=>{let o=JSON.parse(r);return o.version!==Ue||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 ie.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function hd(e){let t=Es(e),n=await lt(t,r=>{let o=JSON.parse(r);return o.version!==Ue||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 ie.stat(t),await jn(e)}catch{}return null}async function Un(e,t){await ie.mkdir(j.dirname(e),{recursive:!0}),await P(e,JSON.stringify(t));try{let r=await ie.stat(e);ys(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{ke.delete(e)}let n=j.dirname(j.dirname(e));if(e===so(n)||e===ao(n)||e===co(n)){let r=lo(e,t.context_fingerprint);await P(r,JSON.stringify(t));try{let c=await ie.stat(r);ys(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{ke.delete(r)}let o=j.dirname(e),i=j.extname(e),s=j.basename(e,i),a=(await ie.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==j.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>j.join(o,c.name));if(a.length>ad){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await ie.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-ad)))await ie.rm(l.path,{force:!0}),ke.delete(l.path)}}}function LE(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function yd(e,t,n){return e===void 0||LE(e,t,n)}function zn(e,t){e&&!e.includes(t)&&e.push(t)}function $n(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function PE(e,t,n){let r=j.join(e,t);try{let o=await ie.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!X(o)&&zn(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function ME(e,t){try{let n=await ie.stat(j.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 bs(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await ME(e,n))))}function oo(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&&$n(o,r.mtime_ms,r.ctime_ms,r.size)})}function FE(e){return Xt.some(t=>e.toLowerCase().endsWith(t))}function $E(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function jE(e,t,n){if(n)for(let r of await Ie({path:e,scope:"project"}))zn(t,r)}function cd(e,t,n,r){if(e)return t&&n?n.collections:r}async function UE(e,t,n){let r=await ie.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=vr(e);await jE(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&$n(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&$n(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&$n(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:cd(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let g=await ie.readFile(e,"utf8"),b=Me(g,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:v=>zn(n.warnings,v)}),E=io(b.metadata);return $E(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:E.light,heavyMetadata:cd(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function zE(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?md(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};yd(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function qE(e,t,n,r){try{let o=await UE(t,n,r);zE(t,n,r,o)}catch{zn(r.warnings,`item_list_item_read_failed:${e}/${j.basename(t)}`)}}function BE(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function GE(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function VE(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function HE(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function WE(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!FE(s))continue;let a=j.join(o,s),c=j.relative(t.pmRoot,a);n.push(qE(r,a,c,t))}return n}async function KE(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!oo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Un(so(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Un(Es(e.pmRoot),{version:Ue,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:j.relative(e.pmRoot,r.item_path),metadata:io(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await id({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await ro(e.pmRoot)}catch{}}async function YE(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 Un(ao(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function XE(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 Un(co(e.pmRoot),{version:Ue,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function ks(e,t,n={}){let r=await hd(e);return n.required!==!0&&(r===null||r.entry_count<fd)?async()=>{}:Ne(e,bE,30,t,!1,!1,3e3)}function ld(e,t){let n=j.relative(e,t);return n===""||n===".."||n.startsWith(`..${j.sep}`)||j.isAbsolute(n)?null:n}async function jn(e){await Promise.all([so(e),ao(e),co(e),ws(e),Es(e)].map(async t=>{await ie.rm(t,{force:!0}),ke.delete(t)})),await ro(e)}async function JE(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await ie.stat(e.mutation.itemPath),n=io(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 QE(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function Ts(e){let t=ld(e.pmRoot,e.itemPath),n=e.previousItemPath?ld(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await jn(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=_d(e.preferredFormat,e.typeToFolder,e.schema,pd()),o=await hd(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await gd(e.pmRoot);if(s.invalid)return await jn(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=QE(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 JE({mutation:e});let l=ud();return await Un(ws(e.pmRoot),{version:Ue,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await bs(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await sd({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:io(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 jn(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ZE(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function dd(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function ev(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function tv(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?md(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);yd(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:j.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function nv(e){return e.forceSourceScan||Ar()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!oo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||dd(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||dd(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ev(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function fo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=pd(),l=_d(t,n,o,c),d=await gd(e);d.invalid&&await jn(e);let u=await RE(e,l,i.cacheDiagnostics),f=s?await NE(e,l):null,p=a?await DE(e,l):null;OE(u,f,p,d.envelope);let _=BE(u,l),g=GE(f,l),b=VE(p,l),E=[...new Set(Object.values(n))],v=await bs(e,E),C=Object.keys(_),A=Math.max(1,Math.floor(i.derivedIndexMinimumItems??fd));if(nv({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:v,entryKeys:C,minimumIndexedItems:A,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:b}))return tv({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:g,previousCollections:b});let O=await Promise.all(E.map(K=>PE(e,K,r))),Q=Ar(),$=HE(),fe={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:Q,previousEntries:_,previousBodies:g,previousCollections:b,state:$};await Promise.all(WE(O,fe));let z=await bs(e,E),pe=oo(v,z)?z:{},I=$.misses.metadata||Object.keys(_).length!==Object.keys($.newEntries).length||!oo(u?.directory_signatures,pe)||u===null?ud():u.source_cursor;return await KE({pmRoot:e,contextFingerprint:l,sourceCursor:I,existingCache:u,previousEntries:_,directorySignatures:pe,state:$,minimumIndexedItems:A}),s&&await YE({pmRoot:e,contextFingerprint:l,sourceCursor:I,existingBodyCache:f,previousBodies:g,state:$}),a&&await XE({pmRoot:e,contextFingerprint:l,sourceCursor:I,existingCollectionsCache:p,previousCollections:b,state:$}),ZE($)}async function bd(e,t,n,r,o){return(await fo(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]="d24d61bf-7db8-5f35-8dbc-5ef93ec8220b")}catch{}})();async function rv(e){try{return await ut.access(e),!0}catch{return!1}}function dt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ov(e,t){e&&(e.includes(t)||e.push(t))}function iv(e){return e??We(B())}function sv(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}function po(e){return new y(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",nextSteps:["Pass the tracker directory itself, usually <workspace>/.agents/pm."]})}function Ss(e){return new y(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",nextSteps:["Grant read and directory-search permission to the tracker root, then retry the SDK read."]})}async function av(e){let t=cn.parse(cn.resolve(e)).root,n=cn.dirname(cn.resolve(e));for(;n!==t;){let r;try{r=await ut.stat(n)}catch(o){if(dt(o,"ENOTDIR"))throw po(e);if(!dt(o,"ENOENT"))throw o;n=cn.dirname(n);continue}if(!r.isDirectory())throw po(e);break}}async function wd(e){let t;try{t=await ut.stat(e)}catch(n){throw dt(n,"ENOENT")?(await av(e),new y(`Tracker root does not exist at ${e}.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",nextSteps:["Confirm the tracker root path and retry the SDK read.","Initialize a tracker before enumerating its item metadata."]})):dt(n,"ENOTDIR")?po(e):dt(n,"EACCES")||dt(n,"EPERM")?Ss(e):n}if(!t.isDirectory())throw po(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Ss(e);try{await(await ut.opendir(e)).close()}catch(n){throw dt(n,"EACCES")||dt(n,"EPERM")?Ss(e):n}}async function Le(e,t,n="pm-",r,o=we){let i=ct(t,n),s=an(t),a=i===s?[i]:[i,s],c=Object.entries(o),l=sv(r);for(let d of a)for(let[u]of c)for(let f of l){let p=Jt(e,u,d,f,o);if(await rv(p))return{id:d,type:u,itemPath:p,item_format:f}}return null}async function Te(e,t={}){let n=await ut.readFile(e.itemPath,"utf8");await Ie({path:e.itemPath,scope:"project"});let r=Me(n,{format:e.item_format,schema:t.schema,extensionFieldNames:iv(t.extensionFieldNames),onWarning:o=>ov(t.warnings,o)});return{raw:n,document:r}}async function qn(e,t,n=we,r,o){return await wd(e),(await bd(e,t,n,r,o)).map(s=>s.metadata)}async function mo(e,t,n=we,r,o,i={}){return await wd(e),(await fo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function Ed(e){return{async get(t){let n=await Le(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Te(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>qn(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function cv(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await ut.readdir(cn.join(e,o));for(let s of i)for(let a of Xt)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function lv(e,t,n,r){let o=ct(t,n),i=await cv(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:St(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function vd(e,t,n,r){let o=await lv(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 dv(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 uv(e){let t=e.typeToFolder??oe(e.settings,B()).type_to_folder,n=await Le(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await vd(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await Ne(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 Te(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=Ai(e.author),d=Mt(e.settings);if(a&&c!==l&&!e.force&&!dv(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 fv(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 pv(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await P(e.originalItemPath,e.originalRaw),await ut.rm(e.effectiveTargetItemPath,{force:!0});return}await P(e.originalItemPath,e.originalRaw)}}async function _o(e){let t=await uv({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=_e(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=_e(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??[]]};l.metadata.updated_at=F();let u=_e(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await pi({pm_root:e.pmRoot,operation:e.op,before:c,after:u,changed_fields:d.changedFields,sdk:Ed({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let f=await gs({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),p="toon",_=kt(u,{format:p,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=Jt(e.pmRoot,u.metadata.type,r.id,p,n),b=Fe(e.pmRoot,r.id),E=await $e("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:g,history_path:b,item_format:p,before:c,after:u,contents:_}),{effectiveTargetItemPath:v,effectiveSerializedAfter:C,skipItemWrite:A}=fv(E,g,_),O=await ks(e.pmRoot,e.author),Q=[];try{A||await P(v,C),!A&&v!==r.itemPath&&await ut.rm(r.itemPath);let fe=Cn({nowIso:u.metadata.updated_at,author:e.author,op:e.op,before:c,after:u,message:e.message});try{await jr(b,fe)}catch(z){throw await pv({skipItemWrite:A,effectiveTargetItemPath:v,originalItemPath:r.itemPath,originalRaw:o}),z}A||(Q=await Ts({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:v,previousItemPath:r.itemPath,document:u}))}finally{await O()}let $=[...await ge({path:v,scope:"project",op:e.op,item_id:u.metadata.id,item_type:u.metadata.type,before:c,after:u,changed_fields:d.changedFields}),...await ge({path:b,scope:"project",op:`${e.op}:history`,item_id:u.metadata.id,item_type:u.metadata.type,before:c,after:u,changed_fields:d.changedFields})];return fi({id:u.metadata.id,op:e.op,item_type:u.metadata.type,previous_status:c.metadata.status,status:u.metadata.status,previous:Sr(c.metadata,d.changedFields),current:Sr(u.metadata,d.changedFields),changed_fields:d.changedFields}),{item:u.metadata,body:u.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...f.warnings,...E.warnings,...Q,...$]}}finally{await 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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function _v(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Mt(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 gv(e){let t=await V(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 Le(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await Te(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 kd(e){let t=e.writeHistoryRaw??P;try{await t(e.historyPath,e.nextHistoryRaw),await He(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await mv.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await He(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function As(e){let t=[..._v({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await Ne(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 gv({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 ln from"node:fs/promises";import{createHash as hv}from"node:crypto";import Sd 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 Ad=4,yv="history-drift-cache.json";function xd(e){return Sd.join(e,"runtime",yv)}async function bv(e){try{let t=await ln.readFile(xd(e),"utf8"),n=JSON.parse(t);return n.version!==Ad||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function wv(e,t,n,r,o){let i=Vr(e),s;try{s=await ln.stat(i)}catch(l){return X(l)||o.unreadableStreams.push(le),!1}let a=o.missingStreams.length,c=await Id({itemId:le,historyPath:i,stat:s,cached:t[le],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.chainOk||o.chainMismatches.push(le),n[le]={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 Cd(e){return hv("sha256").update(e).digest("hex")}async function Ev(e){let t=await ln.readFile(e,"utf8");return Cd(t)}async function vv(e){let t=await ln.readFile(e,"utf8"),n=Cd(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=It(r);return{latestAfterHash:o,chainOk:i.ok,contentHash:n,itemHashVersion:i.item_hash_version??Re}}function kv(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Td(e,t,n){try{let r=await vv(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Id(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(kv(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Td(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await Ev(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??Re},cacheDirty:!1}:{verification:await Td(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Tv(e,t,n,r){let o=Fe(e,t.id),i;try{i=await ln.stat(o)}catch(d){return(X(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await Id({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 xn({metadata:c,body:a},s.verification.itemHashVersion)!==s.verification.latestAfterHash&&r.hashMismatches.push(t.id),s.cacheDirty}async function Sv(e,t){if(!(t.unreadableStreams.includes(le)||t.chainMismatches.includes(le)))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(le)}}async function go(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await bv(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await Tv(e,f,l,r)&&(a=!0);let d=await wv(e,i,s,c,r);if(a||=d,await Sv(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=xd(e);try{await ln.mkdir(Sd.dirname(f),{recursive:!0}),await P(f,JSON.stringify({version:Ad,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?[le]:[]])].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]="cd2a27ec-0f12-591d-ab34-529ddda05063")}catch{}})();async function Od(e,t,n,r){let o=await Le(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Fe(e,o.id),located:o};let i=ct(t,n.id_prefix),s=an(t),a=i===s?[i]:[i,s];for(let c of a){let l=Fe(e,c);if(await D(l))return{id:c,historyPath:l,located:null}}throw new y(`Item ${t} not found`,h.NOT_FOUND)}import Rd from"node:fs/promises";import Nd 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 Av=[{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 Bn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dd(e){return Av.find(t=>t.matches(e))?.kind}function Ld(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=Bn(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=Bn(u)?Dd(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 Pd(e){let t=[];for(let n of await xv(e))try{let r=await Rd.readFile(Nd.join(e,"history",n),"utf8");for(let o of r.split(`
|
|
103
|
+
`)){if(o.trim().length===0)continue;let i=Cv(o);if(i===null||!Bn(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>Bn(a)&&Dd(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function xv(e){try{return(await Rd.readdir(Nd.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function Cv(e){try{let t=JSON.parse(e);return Bn(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]="de9b7f82-0f51-599d-b1fa-2d54e3acbdbc")}catch{}})();function Md(e,t){return t==="body"?e.body:e.metadata[t]}function xs(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)&&xs(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)&&xs(o,n[r]))}function Fd(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 Rn(i.patch))s.add(Fn(c.path)),c.from&&s.add(Fn(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 Iv(e,t,n){let r=$d.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(Fn(_.path));let i=new Set([...o].filter(_=>xs(Md(t,_),Md(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=Fd(e,s),c=Fd(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 Ov(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Te(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=Fi(i.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:ve(s,r)===a,currentItemRawBeforeLock:i.raw,loadedItem:i}}function Rv(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 Nv(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:F(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?$d.compare(e.finalReplay,e.currentItemReplay):[],before_hash:ve(e.finalReplay,e.itemHashVersion),after_hash:ve(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 Dv(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 Lv(e){return As({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})=>kd({historyPath:e.historyPath,nextHistoryRaw:it(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ge({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Cs(e,t,n){let r=te(process.cwd(),n.path);if(!await D(U(r)))throw new y(`Tracker is not initialized at ${r}. Run pm init first.`,h.NOT_FOUND);let o=await W(r),i=oe(o,B()),s=await Od(r,e,o,i.type_to_folder);if(!await D(s.historyPath))throw new y(`No history stream exists for ${s.id}.`,h.NOT_FOUND);let a=await V(s.historyPath),c=await rt(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=Ot(c),d=It(c),u=t.normalizeProvenance?Ld(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=$i(u.entries),p=new Set(u.entries.map(q=>q.item_hash_version).filter(q=>q!==void 0)),_=Ur(u.entries,f),g=await Ov(s,o,c,f),b=_.finalDocument,E=g.currentItemReplay!==null&&ve(b,f)!==ve(g.currentItemReplay,f),v=E&&g.currentItemReplay?Iv(_.entries,b,g.currentItemReplay):void 0,C=[_.entriesRehashed>0,_.entriesPatchRepaired>0,E,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),A=Oe(t.author,o.author_default),O=!!t.dryRun,Q=Rv({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:E}),{rewrittenEntries:$,auditEntryAdded:fe}=Nv({reanchorEntries:_.entries,changed:C,reconcileNeeded:E,currentItemReplay:g.currentItemReplay,finalReplay:b,author:A,message:Q,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...t.auditContext,provenance_normalization:u.receipt}:t.auditContext,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),z=Ot($);if(!z.ok)throw new y(`history-repair produced an invalid rewritten chain (${z.errors.join(", ")}).`,h.GENERIC_FAILURE);let pe=Dv(C,_.skippedOps,v);return C&&!O&&pe.push(...await Lv({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:A,force:t.force,loadedItem:g.loadedItem,historyPath:s.historyPath,rewrittenEntries:$})),{id:s.id,dry_run:O,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:fe,verify_ok:z.ok,verify_errors:z.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},...v?{reconciliation:v}:{},warnings:[...new Set(pe)].sort((q,I)=>q.localeCompare(I)),generated_at:F()}}async function jd(e,t){let n=te(process.cwd(),t.path);if(!await D(U(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,h.NOT_FOUND);let r=await W(n),o=oe(r,B()),i=[],s=await mo(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await go(n,s),c=e.normalizeProvenance?await Pd(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 Cs(p,{...e,auditContext:e.auditContextById?.[p],auditContextById: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}:{},warnings:_.warnings})}catch(_){f.failed+=1,d.push({id:p,outcome:"failed",error:_ instanceof Error?_.message:String(_)})}return e.dryRun||await Di(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:F()}}import ha from"node:fs/promises";import{realpathSync as $S}from"node:fs";import{execFile as jS}from"node:child_process";import ue from"node:path";import{promisify as US}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 Pv=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 Mv(e){if(typeof e!="string")return;let t=e.trim();for(let n of Pv)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Fv(e){let t={};for(let n of e){let r=Mv(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Ud(e){return Object.values(Fv(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 $v=["metadata","resolution"],Is=["metadata","resolution","estimates","lifecycle"],jv="completed";function Os(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function zd(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function qd(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=zd(n.close_reason)??jv;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Os(r)}`,gate:"resolution"})}return t}function Bd(e){let t=[];for(let n of e){let r=zd(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 ${Os(r)}`,gate:"metadata"})}return t}function Gd(e,t){return e.map(n=>{let r=Nl(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 Vd(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 Hd(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 ${Os(n.path)}`})}return t}function Wd(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: ${Is.join(", ")}.`,h.USAGE);return new Set($v)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(Is.includes(o)){n.add(o);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Is.join(", ")}.`,h.USAGE)}return n}function Kd(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 Gn(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 Uv=/^([A-Z][A-Z0-9]*-\d+)\b/;function zv(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Uv.exec(t);return n?n[1]:null}function Yd(e){return typeof e=="string"&&e.trim().length>0}function Xd(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||Yd(r.duplicate_of))continue;let o=zv(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:Yd(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 Jd(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 Qd=3;function Zd(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function eu(e,t,n=Qd){let r=Number.isFinite(n)&&n>=1?Math.floor(n):Qd,o=new Map;for(let i of t){let s=Zd(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(Zd(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 tu(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 qv=/^[a-z][a-z0-9+.-]+:\/\//i;function Vn(e){return qv.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 Bv(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function nu(e){return`${e.item_id} ${e.link_kind}`}function ru(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=Bv(o.classification,r.classification),o.owners.set(nu(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[nu(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 Gv(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ou(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="${Gv(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 Vv="global",Hv="external";function iu(e){let t=e?.trim().toLowerCase();return t===Vv||t===Hv}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6fc5da1-b7d1-5b3c-8033-cecccc7861c3")}catch{}})();function Wv(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function su(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=Wv(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;iu(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 dn from"node:fs/promises";import un 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 Kv(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await dn.readdir(un.join(e,o))}catch{return}for(let s of i)for(let a of Xt)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 Yv(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Ce(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 Rs(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 Xv(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await dn.readdir(un.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 dn.readFile(un.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:Rs("history stream",s)});continue}Yv({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function au(e){let t=Ce(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 Jv(e){let t=[],n=0,r=null;try{r=await V(U(e))}catch(i){n+=1,t.push({path:"settings.json",detail:Rs("configuration file",i)})}if(r!==null){n+=1;let i=au(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await dn.readdir(un.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 dn.readFile(un.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:Rs("configuration file",c)});continue}let a=au(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function cu(e,t,n,r={}){let o=await Kv(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=un.join(e,u.relativePath);return Me(await dn.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 Xv(e,i),d=await Jv(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 Qv}from"node:child_process";import{realpath as Zv}from"node:fs/promises";import lu from"node:path";import{promisify as ek}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 tk=ek(Qv),nk=32*1024*1024,rk=1e4,ok=["search/eval-queries.json"];function Ns(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function ik(e){return`'${e.replaceAll("'","'\\''")}'`}async function sk(e,t=Zv){return t(e).catch(()=>lu.resolve(e))}async function du(e){let t=await sn(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 sk(e),r=Ns(lu.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=ql.map(i=>`${r}/${Ns(i)}`);try{let{stdout:i}=await tk("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:nk,windowsHide:!0,timeout:rk}),s=new Set(ok.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(Ns(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=>ik(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import la from"node:fs/promises";import da from"node:path";import{Option as AG}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]="7426082f-94a6-5b4e-9748-d3faab2fe1d4")}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]="d5003dd5-f208-5734-9711-dff935d8c851")}catch{}})();var fn="-",uu=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 Ds(e){return e.replace(/\r\n/g,`
|
|
104
|
+
`)}function fu(e){let t=Ds(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
|
|
105
105
|
`);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
|
|
106
|
-
`)}function
|
|
107
|
-
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=
|
|
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]=
|
|
109
|
-
${i}`;continue}return null}return n}function fn(e,t){let n=iu(e).trim();if(!n)throw new y(`${t} cannot be empty`,g.USAGE);let r=HE(n);if(r)return r;let o={},i,s=qE(n);for(let a of s){let c=BE(a);if(c>0){let l=a.slice(0,c).trim(),d=su(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&ou.has(i.toLowerCase())){o[i]=`${o[i]},${a.trim()}`;continue}throw new y(VE(e,t),g.USAGE)}return o}var WE=/^[A-Za-z]:[\\/]/,KE=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Os(e){let t=e.trim();return WE.test(t)?!1:KE.test(t)}function pn(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(", ")}.`,g.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.`,g.USAGE);e[s]=e[i],delete e[i]}}}async function YE(e){if(process.stdin.isTTY===!0)throw new y(`${e} value "${un}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,g.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(Is(r))}),process.stdin.on("error",o=>{n(o)})})}function Rs(){let e,t,n=async i=>{if(t&&t!==i)throw new y(`Only one option may use "${un}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);return t=i,e||(e=YE(i)),await e};return{resolveValue:async(i,s)=>{if(i!==void 0)return i.trim()!==un?i:await n(s)},resolveList:async(i,s)=>{if(!i)return;let a=i.map((d,u)=>d.trim()===un?u:-1).filter(d=>d>=0);if(a.length===0)return i;if(a.length>1)throw new y(`${s} accepts "${un}" stdin token at most once per command invocation`,g.USAGE);let c=await n(s),l=[...i];return l[a[0]]=c,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]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var XE={critical:0,high:1,medium:2,low:3,minimal:4},JE=Object.keys(XE),DF=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${JE.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 XF=new Map(Do.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 hk}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 yk=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,nj=new RegExp(`\\b(${yk.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var rj=hk(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 sj=new Map([[g.USAGE,"invalid_command_usage"],[g.NOT_FOUND,"item_not_found"],[g.CONFLICT,"lock_conflict"],[g.DEPENDENCY_FAILED,"dependency_failed"]]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffe56aed-b794-5bf4-99fd-e3c5fe065163")}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 wk=[{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"}],gj=new Map(wk.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 Tj=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 Ns(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 Fj 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 kk from"node:crypto";import Ds 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 Qj=Ds.join("runtime","telemetry","events.jsonl"),Zj=Ds.join("runtime","telemetry","state.json"),e1=Ds.join("runtime","telemetry","otel-spans.jsonl");var t1=3600*1e3;var n1=globalThis.fetch,Tk=["user","automation","test","dogfood"],r1=Promise.resolve(),o1=Promise.resolve();var i1=new Set(Tk);var s1=kk.randomUUID();var pu="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",a1=new RegExp(`\\b(${pu})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),c1=new RegExp(`(--${pu})(=|\\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]="a678b9f8-ba36-5127-877f-96bb4acc38c5")}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]="940f11a8-f40d-5169-ba74-e91920d32c4a")}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]="3b9b9ebe-8d98-5983-8257-b7b77c7e6194")}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]="f7e87e15-b5f3-53ab-86e2-768e94d5d329")}catch{}})();var Ls=[{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"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"test",keys:["test"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],mu=Ls.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),_u=Ls.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Ps=[{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 dependencies by id or id=<id>,kind=<value>,source_kind=<value> selectors (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"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"test",keys:["test"],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},{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}],Ms=Ps.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),gu=Ps.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]="e2028eff-b29e-5850-87b1-4a3e06f28964")}catch{}})();function re(e){return e.map(t=>({...t}))}var Fs=[{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"}],hu=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],Nk=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...hu],yu=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],Dk=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],Lk=[...Fs,...yu],bu=[{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"}],Pk=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],wu=[{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"}],$s=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...re(Fs),...re(Nk),{param:"ids",flag:"--ids"},...re(yu),...re(Pk),...re(bu),...re(wu),{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"}],js=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...re(Lk)],Us=[{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"},...re(Fs),...re(hu),...re(Dk),...re(bu),...re(wu),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],vu=[{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"}],po=re(vu),Eu=[{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"}],zs=re(Eu),ku=[{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"}],qs=re(ku),Bs=[{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"}],Gs=re(Bs),Vs=re(Bs);var Hs=[{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}],Ws=[{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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function Ks(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]="c82d9b50-274f-585d-be0e-9a0c5067b9e9")}catch{}})();var Tu=ei.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),Mk=[...Tu,{flag:"--version"}],Su=[{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"}],Au=[{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"}],xu=Zs([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{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:"--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"},...Su,{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"])),Cu=[{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}],Iu=[{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 Zs(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var Ou=[{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"}],Ru=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Nu=[{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"}],Du=[{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"}],Lu=[{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"}],Pu=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],Mu=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Fu=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],$u=[{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"}],ju=[{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"}],Uu=[{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"}],zu=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],qu=[{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"}],Bu=[{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"}],Gu=[{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"}],ea=[{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"}],Ye=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],Vu=[...Ye,{flag:"--capability"}],Ys=[...ea,{flag:"--declarative"}],Fk=[...Vu,{flag:"--declarative"}];var $k=[...Ye,{flag:"--markdown"},{flag:"--output"}];var jk=[...Ye,{flag:"--dry-run"}],Uk=[...Ye,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],zk=[...Ye,{flag:"--watch"}],qk=[...Ye,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],Bk=[...Ye,{flag:"--fields",list:!0}],Gk=[...Ye,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Hu=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Wu=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var Ku=[{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"}],Yu=[{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"},...Au,{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"}],Xu=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Ju=[{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"]}],Qu=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Zu=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ef=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],tf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],nf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],rf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],of=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],ta=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...of],sf=ta,af=[{flag:"--at"},{flag:"--text"},...of],cf=[{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:"--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"}],lf=[{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:"--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"}],df=[{flag:"--limit"}],uf=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],ff=[{flag:"--dry-run"},{flag:"--scope"}],pf=[{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"}],mf=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],_f=[{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"}],gf=[{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"}],hf=[{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"}],yf=[{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"}],bf=[{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"}],wf=[{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"]}],Xs=[{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"},...yf,...bf,{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"},{flag:"--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"}],vf=[{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"}],Ef=[{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"}],kf=[{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"}],Tf=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Sf=[{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"},...wf,...yf,{flag:"--fixed_version"},...bf,{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"},{flag:"--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"}],Af=[{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"},...Au,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...wf,{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"}],Js=[{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"}],xf=[{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"}],Cf=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{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"}],Qs=Zs([{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"])),If=[{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"}],Of=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],Rf=[{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}],Nf=[{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"}],Df=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],ft=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],Lf=[{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"]}],Pf=Zs([{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"},...Su],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Mf=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Ff=[{flag:"--eager-tags"}];var Vk=["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],Yq=new Map([...Vk.map(e=>[e,xu]),["templates",Xs],["cal",Js],["ctx",Qs],["test-runs-worker",uf],["init",Bu],["config",Gu],["extension",ea],["package",Ys],["packages",Ys],["install",Hu],["upgrade",Wu],["create",Xs],["item mutate",vf],["item complete",Ef],["copy",kf],["focus",Tf],["aggregate",Cu],["calendar",Js],["context",Qs],["get",If],["guide",Of],["search",Pf],["next",Lf],["eval",Df],["workspace",ft],["workspace snapshot",ft],["workspace snapshot create",ft],["workspace snapshot list",ft],["workspace snapshot inspect",ft],["workspace snapshot restore",ft],["workspace snapshot delete",ft],["history",Lu],["history-redact",Mu],["history-repair",Fu],["history-author-acknowledge",$u],["history-compact",ju],["merge",Pu],["schema",Uu],["profile",zu],["plan",qu],["activity",xf],["events",Cf],["restore",Qu],["update",Sf],["update-many",Af],["close",Ku],["close-many",Yu],["delete",Zu],["append",Xu],["comments",Iu],["notes",Ou],["learnings",Ru],["files",Nu],["docs",Du],["deps",Rf],["graph",Nf],["test",cf],["test-all",lf],["telemetry",df],["health",_f],["assurance",hf],["validate",gf],["gc",ff],["stats",pf],["duplicates",mf],["contracts",Mf],["completion",Ff],["claim",Ju],["release",ef],["start-task",tf],["pause-task",nf],["close-task",rf],["meet",ta],["event",sf],["remind",af]]);(function(){try{var e=typeof window<"u"?window:typeof 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 $f={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},jf={if:{required:["field"]}};Reflect.set(jf,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var Uf={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:[jf],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:$f,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:$f,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]="cb6f6915-307c-58e7-a892-3dff4c7ae399")}catch{}})();var Vn={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:Nr,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"},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"},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"}},zf={assurance:{definition:Uf,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote"]},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"}}]}},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}}},Hk=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],na={subcommand:{type:"string",enum:[...Hk]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...Ea]},mode:{type:"string",enum:[...va]},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:[...sr]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...ka]},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"}}]}},ra={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"]}},Hn={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."},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"]}},qf={assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, or promote.",examples:["list","run","derive","promote"]},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]}},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]="1d6089b2-ab59-59ad-a475-9a6ef1356b40")}catch{}})();var Kk=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],Yk=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],Xk=new Set(["action","cwd","options",...Object.keys(Vn).filter(e=>e!=="severity")]);var Jk={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},Wf=["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"],lB=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(Zt.filter(e=>e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function be(e){return Ks(e)}var Qk=be([...zs.map(e=>e.param),...po.map(e=>e.param),"assignee","closeReason","completedAt"]),Kf=be([...qs.map(e=>e.param),...po.map(e=>e.param),"force"]),Zk=be([...Gs.map(e=>e.param),...Kf.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),eT=be([...Vs.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),Bf=be([...Ws.map(e=>e.param),"past","section"]),tT=be([...Hs.map(e=>e.param),"stream"]),pt=be([...$s.map(e=>e.param),"includeBody","noTruncate","strictRead","compact","brief","full"]),mt=[[{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"}}]],nT=[[{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}}]],rT=be([...js.map(e=>e.param),"count","completion","includeUnparented"]),oT=be(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Us.map(e=>e.param)]),Gf=be(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),de=["author","message","force"],Yf=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],Wn=["author","assignee","message","force"],iT=["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 Vf(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:iT}}}var Hf={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},mo={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"]},...Vf("extension"),...Vf("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:Qk},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:pt,mutuallyExclusiveWhen:mt},"list-all":{optional:pt,mutuallyExclusiveWhen:mt},"list-draft":{optional:pt,mutuallyExclusiveWhen:mt},"list-open":{optional:pt,mutuallyExclusiveWhen:mt},"list-in-progress":{optional:pt,mutuallyExclusiveWhen:mt},"list-blocked":{optional:pt,mutuallyExclusiveWhen:mt},"list-closed":{optional:pt,mutuallyExclusiveWhen:mt},"list-canceled":{optional:pt,mutuallyExclusiveWhen:mt},aggregate:{optional:rT},guide:{optional:["list","format","depth"]},context:{optional:Bf},ctx:{optional:Bf},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:oT,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter"]},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:Hf,event:Hf,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...Gf,"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",...de],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...de],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",...de]},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",...Wf,"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",...de]},activity:{optional:tT},restore:{required:["id","target"],optional:de},update:{required:["id"],optional:Kf,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:Zk,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...Yf,...de]},"close-many":{optional:eT},delete:{required:["id"],optional:["dryRun",...de]},append:{required:["id","body"],optional:de},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...de]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full",...de],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...de]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...de],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...de],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","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...de]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","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:nT},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...Gf,...Wn],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:Wn},"start-task":{required:["id"],optional:Wn},"pause-task":{required:["id"],optional:Wn},"close-task":{required:["id"],optional:["text","validateClose",...Wn]}},sT=Object.freeze(Object.fromEntries(Zt.map(e=>[e,mo[e]])));function Xf(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function aT(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=Hn[e];return{...n,description:r?.description??Xf(e),...r?.examples?{examples:r.examples}:{}}}function cT(e,t){if(e==="plan"&&Object.prototype.hasOwnProperty.call(ra,t))return ra[t];let n=qf[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:Hn[t]}function lT(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=cT(e,t);return{...r,description:o?.description??Xf(t),...o?.examples?{examples:o.examples}:{}}}function dT(e,t){let n=zf[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(na,t)?na[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:Vn[t]}function uT(e,t){let n={action:{const:e,description:Hn.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=dT(e,r);o&&(n[r]=lT(e,r,o))}return n}function fT(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 pT(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:be(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 Jf(e){if(!Object.prototype.hasOwnProperty.call(mo,e))return;let t=mo[e],n=Jk[e]??[];return be(["action",...Kk,...Rr(e)!==void 0?Yk:[],...n,...t.required??[],...t.optional??[]])}function mT(e){let t=mo[e],n=be(t.required??[]),r=Jf(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:uT(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=fT(e,t.oneOfRequired));let i=pT(t);return i.length>0&&(o.allOf=i),o}function Qf(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 oa="4.7.0",Zf=oa.split(".")[0],ep="1.3.0",_T=Qf(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Zf}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":oa,type:"object",oneOf:Zt.map(e=>mT(e))}));function gT(e,t){let n=aT(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 hT(){let e={action:{type:"string",description:Hn.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(Vn).sort())e[t]=gT(t,Vn[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":ep,type:"object",additionalProperties:!1,required:["action"],properties:e}}var yT=Qf(hT);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b227cb2-a30d-5384-b9c2-558603181c67")}catch{}})();var _B=new Set([...jc,...Uc]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="969b5bd2-e7de-5db8-bef2-6748675a100c")}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]="8d60b13c-c58a-506f-adc9-2414dd69edef")}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]="0e153ece-4fc0-5134-97f0-c2315aff0031")}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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var CT="2026-07-15T06:22:12.276Z",IT=Date.parse(CT),OT=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],tp=e=>typeof e=="string"?e:"",RT=e=>{let t=e??{},n=tp(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(tp(t.ts))>=IT);return OT[r][o]};function NT(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 h=RT(_);if(h!=="attributed"){if(d+=1,h==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[h]+=1,o&&h==="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 DT(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 np=async(e,t=20,n=!1)=>{let r=sa.join(e,"history"),o;try{o=(await ia.readdir(r)).filter(v=>v.endsWith(".jsonl")).sort((v,E)=>v.localeCompare(E))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,m=0,_="_workspace.jsonl",h=new Set;if(o.includes(_))try{h=DT(await ia.readFile(sa.join(r,_),"utf8"))}catch{h=new Set}for(let v of o){let E;try{E=await ia.readFile(sa.join(r,v),"utf8")}catch{continue}let I=v.slice(0,-6),A=NT(I,E,t-s.length,h,n);c+=1,l+=A.checked_events,d+=A.unknown_event_count,u+=A.legacy_unknown_event_count,f+=A.actionable_unknown_event_count,m+=A.acknowledged_actionable_event_count,A.unknown_event_count>0&&i.add(I),s.push(...A.samples),n&&a.push(...A.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((v,E)=>v.localeCompare(E)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import LT from"node:fs/promises";import Se from"node:path";import PT 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]="256b39b7-882e-553c-9dea-813bfd363dd7")}catch{}})();var MT=["path","scope","note"],FT=["pattern","glob","path","scope","note"],$T=["path"],jT=["from","to"],UT=new Set(["note","scope"]);function op(e){let t=e??"project";if(!Lo.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Lo.join(", ")} (default: project).`,g.USAGE);return t}function ip(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("=")||Os(e)}function zT(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||ip(n)||!n.includes(",")?[t]:Ns(n)})}function qT(e,t){return e?zT(e).map(n=>{let r=n.trim(),o=ip(r)?fn(n,"--add"):{path:r};if(pn(o,"--add",MT),!o.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return{path:o.path,scope:op(o.scope),note:o.note?.trim()||void 0}}):[]}function BT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=fn(n,"--add-glob");pn(r,"--add-glob",FT);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:o,scope:op(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function GT(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=fn(n,"--remove"),o=Object.keys(r).filter(i=>UT.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>".`,g.USAGE);if(pn(r,"--remove",$T),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function VT(e){return e?e.map(t=>{let n=fn(t,"--migrate");pn(n,"--migrate",jT);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:o}}):[]}function Kn(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 HT(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>Kn(i.path,n))),o=[...new Set(t.map(i=>Kn(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.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function _o(e){return e.split(Se.sep).join("/")}function aa(e,t,n=process.cwd()){let r=e.trim();if(Gn(r))return r;if(Se.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return _o(r.replaceAll("\\",Se.sep));let o=Se.relative(t,n);return o.startsWith(`..${Se.sep}`)||o===".."||Se.isAbsolute(o)?_o(Se.normalize(r)):_o(Se.relative(t,Se.resolve(n,r)))}async function WT(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=Se.isAbsolute(o.pattern),s=await PT(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>aa(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 KT(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)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function YT(e){return`${e.path}::${e.scope}`}function sp(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function ap(e){return[...new Map(e.map(t=>[YT(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function XT(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(Gn(a)){s.push(a.trim());continue}let c=Se.isAbsolute(a)?a:Se.resolve(t,a);try{(await LT.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&Mo(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 JT(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=Kn(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=Kn(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>Kn(s,r)),count:o}}function QT(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=ap(e);return r?o:sp(o)}async function rp(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 XT(t,e.workspaceRoot):void 0}}async function go(e,t,n,r){let{metadataKey:o}=r,i=Rs(),s=te(process.cwd(),n.path),a=Qo(s),c=process.cwd();if(!await N(U(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,g.NOT_FOUND);let l=await W(s),d=oe(l,B()),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"),h=qT(u,r.bareNoun).map(q=>({...q,path:aa(q.path,a,c)})),b=BT(f),v=await WT(b,a,c),E=KT([...h,...v],t.note,h.length>0||b.length>0),I=GT(m).map(q=>aa(q,a,c)),A=VT(_);if(HT(E,I,A),!(E.length>0||I.length>0||A.length>0)){let q=await Le(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!q)throw new y(`Item ${e} not found`,g.NOT_FOUND);let K=(await Te(q,{schema:l.schema})).document.metadata[o]??[];return rp({id:q.id,artifacts:K,changed:!1,options:t,workspaceRoot:a})}let Q=Oe(t.author,l.author_default),$=await uo({pmRoot:s,settings:l,id:e,op:r.op,author:Q,message:t.message,force:t.force,skipNoop:!0,mutate(q){let C=q.metadata,K=C[o]??[],ma=[...K],Xn=JT(ma,E,I,A),ko=QT(ma,Xn.adds,Xn.removes,r.supportsAppendStable&&t.appendStable===!0);ko.length>0?C[o]=ko:delete C[o];let _a=!ve(K,ko);return{changedFields:_a?[o]:[],warnings:_a&&Xn.count>0?[`path_migrations_applied:${Xn.count}`]:[]}}}),fe=$.item[o]??[],z=$.warnings.find(q=>q.startsWith("path_migrations_applied:")),pe=z?Number(z.slice(24)):0;return rp({id:$.item.id,artifacts:fe,changed:$.changedFields.includes(o),migrationsApplied:pe,options:t,workspaceRoot:a})}function ho(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 cp(e,t,n){let r=await go(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ho(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]="515cd35c-8e0e-51d4-8ad9-1cea5be8a572")}catch{}})();async function lp(e,t,n){let r=await go(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ho(r,"files")}import{readFileSync as ZT}from"node:fs";import yo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var eS=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),fp=new Set(["--pm-path","--path","--author"]),tS={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"])},nS=new Set(["-p","--package"]),rS=new Set(["-c","--call"]),oS=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),iS=new Set(["-C","--prefix","--userconfig","--cache"]);var sS=new Set(["exec","x"]);function aS(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function cS(e,t=process.cwd()){let n=lS(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(dp(r)||up(r,t))return o;if(r==="node"&&o[0]&&up(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?ca(o):r==="pnpm"?fS(o):r==="npm"?pS(o):null;return i&&(dp(i.command)||uS(i.command))?i.args:null}var pp=(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 aS(i)){let c=cS(a),l=c?mS(c):null,d=l&&eS.has(l.subcommand)?_S(l.remaining,tS[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 lS(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 dp(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function dS(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 uS(e){let t=dS(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function up(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=yo.resolve(t,e);try{return JSON.parse(ZT(yo.join(yo.dirname(yo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function ca(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(rS.has(r)){t+=1;break}t+=nS.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function mp(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 fS(e){let t=mp(e,oS);return t?.subcommand!=="dlx"?null:ca(t.args)}function pS(e){let t=mp(e,iS);return!t||!sS.has(t.subcommand)?null:ca(t.args)}function mS(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(fp.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function _S(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("=")&&(fp.has(r)||t.has(r))&&(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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function _p(e){return e.includeBody?lo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):zn(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 gS=5;async function gp(e,t,n){let r=await fo(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:gS,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]="b8c4707f-5445-5079-96e5-dc0dbd649b34")}catch{}})();var wS=["src","tests","docs"],vS=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],ES=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),kS=["resolution","expected_result","actual_result"],TS=["default","tracked-all","tracked-all-strict"],hp=["core","strict","custom"],wo=["off","warn","error"];var da=["author","acceptance_criteria","estimated_minutes","close_reason"],kp=[...da,"reviewer","risk","confidence","sprint","release"],pa=Array.from(new Set(kp)),SS={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"},AS={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"},xS={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"},CS={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"},IS={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"},OS=32*1024*1024,RS=1e4,Tp=40,ht=5,NS=4096,DS=255,LS=bS(yS);function Sp(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Sp(r):r);return t}function PS(e){return{...e,checks:e.checks.map(t=>({...t,details:Sp(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 $t(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function yp(e){return $t(e).replace(/\/+$/,"")}function ze(e){let t=se(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Eo(e,t){return vt(e,t)??e}function Yn(e,t){return t.terminal_statuses.has(Eo(e,t))}function _t(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function bo(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function MS(e){let t=_t(Ro),n={blocked_reason:_t(yt.blocked_reason),resolution:_t(yt.resolution),actual_result:_t(yt.actual_result)},r=_t(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:_t(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:_t(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:_t(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:bo(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:bo(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:bo(o.resolution,n.resolution)?"default":"settings",actual_result:bo(o.actual_result,n.actual_result)?"default":"settings"}}}function FS(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(hp.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${hp.join(", ")}.`,g.USAGE)}function $S(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(wo.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${wo.join(", ")}.`,g.USAGE)}function jS(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(wo.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${wo.join(", ")}.`,g.USAGE)}function US(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>SS[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function zS(e,t,n){let r=US(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...da],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...kp],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:[...da],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var qS=new Set(["acceptance_criteria","estimated_minutes"]);function BS(e,t,n,r){return!r&&qS.has(t)&&Yn(e.status,n)?!1:t==="author"?!se(e.author):t==="acceptance_criteria"?!se(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Eo(e.status,n)===n.close_status&&!se(e.close_reason):t==="reviewer"?!se(e.reviewer):t==="risk"?!se(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!se(e.confidence):t==="sprint"?!se(e.sprint):!se(e.release)}function GS(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: ${TS.join(", ")}.`,g.USAGE)}function VS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return ue.resolve(t);let n=ue.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return ue.dirname(ue.dirname(n));let o=ue.resolve(process.cwd()),i=bp(n),s=bp(o),a=ue.relative(i,s);return a.length===0||!a.startsWith("..")&&!ue.isAbsolute(a)?n:o}function bp(e){try{return hS.native(e)}catch{return ue.resolve(e)}}function HS(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ap(e,t,n){let r=t.length>0?ue.join(e,t):e,o;try{o=await fa.readdir(r,{withFileTypes:!0})}catch(i){if(X(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?ue.join(t,i.name):i.name;if(i.isDirectory()){if(ES.has(i.name))continue;await Ap(e,s,n);continue}i.isFile()&&n.push($t(s))}}async function wp(e){let t=[];for(let n of wS)await Ap(e,n,t);for(let n of vS){let r=ue.join(e,n);try{(await fa.stat(r)).isFile()&&t.push($t(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function WS(e){try{let{stdout:t}=await LS("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:OS,windowsHide:!0,timeout:RS}),n=t.split("\0").map(r=>$t(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function KS(e,t){let n=new Set,r=yp(jt);r.length>0&&n.add(r);let o=yp(ue.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function vp(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function YS(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await WS(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await wp(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await wp(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function J(e,t=ht){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function gt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=J(e,Tp);return{values:n.values,truncated:n.truncated,total:e.length}}var XS={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},JS={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function QS(e){let t=e.missing_fields.map(n=>`${XS[n]} "${JS[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function ZS(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"):Dd(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 eA(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 tA="validate_metadata_duplicate_issue_codes";function nA(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ht,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:[`${tA}:${e.length}`]}}function rA(){return Object.fromEntries(pa.map(e=>[e,[]]))}function oA(e,t,n){let r=rA();for(let o of e)for(let i of pa)BS(o,i,t,n)&&r[i].push(o.id);return r}function iA(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${AS[o]}:${i.length}`)}return r.push(...n),r}function sA(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=xS[r];n[s]=i}return n}function aA(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 cA(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=CS[o],a=IS[o];if(!s||!a)continue;let c=J(i,r?i.length:ht);e[s]=c.values,e[a]=c.truncated}}function lA(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:se(n.get(o)?.resolution)})):[]}function dA(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:se(n.get(o)?.type)})):[]}function uA(e,t,n,r){let o=new Map(e.map(b=>[b.id,b])),i=t.profile==="strict",s=oA(e,n,i),a=Bd(e),c=nA(a,r),l=iA(t,s,c.warnings),d=sA(t,s),u=aA(t,s,o),f=Gd(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:[...pa],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]),cA(m,t,s,r);let _=lA(t,s,o),h=dA(t,s,o);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:m},warnings:l,closeReasonBackfillRows:_,estimateBackfillRows:h}}function fA(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(Eo(f.status,t))),i=[],s=[];for(let f of o){let m=kS.filter(_=>!se(f[_]));m.length!==0&&(i.push({id:f.id,missing_fields:m}),s.push({id:f.id,missing_fields:m,close_reason:se(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:ht,l=J(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>QS(f)),u=J(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 pA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mA(e,t="pm",n=Jt()){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=ze(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=ze(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>ze(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=ze(i.definition_of_ready);return gA(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function _A(e,t,n){let r=Zd(e,n?d=>Yn(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:ht,a=J(o,s),c=J(i,s),l=J(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 gA(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${pA(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 xp(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 Cp(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=>{let c=(t.get(a)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&o.length>1)return o.push(n),!0;if(!i.has(l)){if(i.add(l),o.push(l),s(l))return!0;o.pop(),i.delete(l)}}return!1};return s(n)?[...o]:[...e,n]}function hA(e,t="pm"){let n=mA(e,t),r=xp(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>Cp(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function yA(e,t=Jt()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));return[...e].sort((i,s)=>i.id.localeCompare(s.id)).forEach(i=>{let s=r.get(i.id),a=ze(i.parent),c=a?n.get(a.toLowerCase()):void 0;c&&s.push(c),(i.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?r.get(u).push(i.id):s.push(u))})}),r.forEach((i,s)=>{r.set(s,[...new Set(i)].sort((a,c)=>a.localeCompare(c)))}),r}function bA(e){let t=yA(e),n=xp(t),r=[...new Set(n.flat())].sort((i,s)=>i.localeCompare(s)),o=n.map(i=>Cp(i,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:o}}function wA(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 vo(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function vA(e,t){let n=vo(e).split("/").filter(Boolean),r=vo(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function EA(e,t){let n=vo(t),r=vo(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=vA(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 kA(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function TA(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=$t(s.path);if(a.length===0||a===e)return;let c=EA(e,a);c!==null&&kA(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 SA(e,t){return e.map(n=>{let r=wA(n),o=r==="docs_unowned"?"docs":"files",i=TA(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 AA(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function xA(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=ze(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function CA(e,t,n,r,o){let i=ze(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&&!Yn(s.status,o)}}function IA(e,t,n,r){let o=ze(e.blocked_by),i=ze(e.blocked_reason),s=i?.toLowerCase(),a=Eo(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 OA(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=>!Yn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=xA(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=ze(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&Yn(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(CA(c,u,o,i,n))),t){let f=IA(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 RA(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 Ep(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function NA(e,t,n,r,o,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Ep("validate_lifecycle_dependency_cycles",n,o),c=Ep("validate_hierarchy_parent_cycle",r,i);return[...s,...a?[a]:[],...c?[c]:[]]}function DA(e){let t=$t(e);return t.length>NS||t.split(/[\\/]/).some(n=>n.length>DS)}async function LA(e,t){let n=ue.isAbsolute(t)?t:ue.resolve(e,t);if(DA(n))return!1;try{let r=await fa.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return HS(r,["ENOENT","ENOTDIR"])}}async function PA(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(Gn(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=$t(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await LA(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function MA(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:KS(t,n),d=l.length===0?[]:e.candidateFiles.filter(m=>vp(m,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(m=>!vp(m,l)),f={};if(d.length>0){let m=gt(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 FA(e,t,n,r,o,i,s,a="pm"){let c=OA(e,t,o,i);RA(c);let l=hA(c.activeItems,a),d=bA(e),u=NA(c,t,n,r,l.cycle_count,d.cycle_count),f=s?Number.POSITIVE_INFINITY:ht,m=J(c.closureLikeRows.map(O=>`${O.id}:${O.fields.join(",")}`),f),_=J(c.terminalParentRows.map(O=>`${O.id}:${O.parent_id}:${O.parent_status}`),f),h=J(c.staleBlockerRows.map(O=>`${O.id}:${O.status}:${O.reasons.join(",")}`),f),b=J(l.cycle_item_ids,f),v=J(l.cycle_sample_paths,f),E=J(d.cycle_item_ids,f),I=J(d.cycle_sample_paths,f),A=l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="error";return{check:{name:"lifecycle",status:A?"error":u.length===0?"ok":"warn",ok:!A&&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:h.values,stale_blocker_rows_truncated:h.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:b.values,dependency_cycle_item_ids_truncated:b.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:E.values,parent_cycle_item_ids_truncated:E.truncated,parent_cycle_sample_paths:I.values,parent_cycle_sample_paths_truncated:I.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 $A(e,t,n,r,o,i){let s=await PA(e,t),a=new Map(e.map(C=>[C.id,C])),c=[...new Set(s.missingLinkedPaths)].sort((C,K)=>C.localeCompare(K)),l=await YS(t,r),d=MA(l,n,t,r,o,i),u=d.candidateFiles.filter(C=>!s.linkedProjectPaths.has(C)),f=SA(u,e),m=Wd(c,d.candidateFiles),_=new Map(m.map(C=>[C.path,C.classification])),h=m.filter(C=>C.classification==="moved").length,b=s.staleLinkRows.map(C=>({...C,classification:_.get(C.path)??"deleted"})).sort((C,K)=>C.item_id.localeCompare(K.item_id)||C.path.localeCompare(K.path)||C.link_kind.localeCompare(K.link_kind)),v=[];d.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&v.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&v.push(`validate_files_orphaned_paths:${u.length}`);let E=[...s.remoteLinkedPaths].sort((C,K)=>C.localeCompare(K)),I=gt(E,i),A=gt(c,i),O=gt(u,i),Q=gt(f.map(C=>`${C.path}:${C.classification}:owner_candidate=${C.owner_candidate?.id??"unowned"}`),i),$=i?f:gt(AA(f),!1).values,fe=gt(Kd(m),i),z=b.map(C=>({item_id:C.item_id,path:C.path,link_kind:C.link_kind,classification:C.classification})),pe=Xd(z,C=>{let K=a.get(C);return K?{type:K.type,title:K.title,status:K.status}:void 0}),q=i?pe:gt(Jd(pe),!1).values;return{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.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:Tp,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:E.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:A.total,missing_linked_paths:A.values,missing_linked_paths_truncated:A.truncated,missing_linked_paths_moved_count:h,missing_linked_paths_deleted_count:c.length-h,missing_linked_path_classifications:fe.values,missing_linked_path_classifications_truncated:fe.truncated,missing_linked_path_rows_count:pe.length,missing_linked_path_rows:q,orphaned_paths_count:u.length,orphaned_paths_total:O.total,orphaned_paths:O.values,orphaned_paths_truncated:O.truncated,orphaned_path_classifications:Q.values,orphaned_path_classifications_truncated:Q.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:$}},warnings:v,staleLinkPruneRows:b}}function jA(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),o=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${o}`}function UA(e,t,n){let r=new Set(e.map(b=>b.id.toLowerCase())),o=0,i=0,s=new Set,a=[],c=e.flatMap(b=>(b.tests??[]).map(v=>({item:b,linkedTest:v})));for(let{item:b,linkedTest:v}of c){if(typeof v.command!="string"||v.command.trim().length===0)continue;o+=1;let E=pp(v.command,t);if(E.length!==0){i+=E.length;for(let I of E)s.add(I),r.has(I.toLowerCase())||a.push(jA(b.id,I,v.command))}}let l=[...new Set(a)].sort((b,v)=>b.localeCompare(v)),d=[...new Set(l.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,v)=>b.localeCompare(v)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],f=n?Number.POSITIVE_INFINITY:ht,m=J(l,f),_=J(d,f),h=J([...s].sort((b,v)=>b.localeCompare(v)),f);return{check:{name:"command_references",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:i,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:h.values,unique_referenced_pm_ids_truncated:h.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:_.values,stale_pm_ids_truncated:_.truncated,stale_pm_id_reference_rows:m.values,stale_pm_id_reference_rows_truncated:m.truncated}},warnings:u}}function zA(e,t){let n=$a(e.map(c=>({ref:c.id,version:Ma(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:ht,i=J(n.outdated,o),s=J(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:dr,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 ua="pm validate auto-fix";async function qA(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:ua};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.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function la(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function BA(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>la(a)===null))try{await qA(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>la(a)!==null)){let a=la(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 lp(a.item_id,{remove:c,message:ua},t):await cp(a.item_id,{remove:c,message:ua},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}async function GA(e,t,n,r){let o=await tu(e,new Set(t.map(h=>h.id)),n,{schema:r.schema,extensionFieldNames:We(B())}),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 ru(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ds(e,Xr(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await on(e),d=l===null?null:await us(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 rn(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:f,lossless:m}=jr(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(h=>h.item_id))].sort((h,b)=>h.localeCompare(b)),lossless_merge_receipt_count:m.length,lossless_merge_receipt_items:[...new Set(m.map(h=>h.item_id))].sort((h,b)=>h.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 Xe(e,t,n){n&&ZS(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function VA(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=uA(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,Xe(t,o,n)}if(e.requestedChecks.has("resolution")){let o=fA(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,Xe(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=FA(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,Xe(t,o,n),Xe(t,_A(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await $A(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,Xe(t,o,n)}return e.requestedChecks.has("command_references")&&Xe(t,UA(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&Xe(t,await gp(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Xe(t,zA(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Xe(t,await GA(e.pmRoot,e.items,oe(e.settings,B()).type_to_folder,e.settings),n),t}function HA(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Md(t.closeReasonBackfillRows)),r.push(...Pd(t.resolutionBackfillRows)),r.push(...Fd(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...$d(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...jd(t.staleLinkPruneRows)),r}async function WA(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=HA(e,t,n),{applicable:a,gated:c}=zd(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await BA(a,o,i);d.push(...f.applied.map(Bn)),u.push(...f.failed.map(({fix:m,error:_})=>({...Bn(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(Bn),applied_fixes:d,gated_fixes:c.map(f=>({...Bn(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Ip(e,t,n={}){xc(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).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let o=Ud(e.fixScope),i=te(process.cwd(),t.path);if(!await N(U(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let s=await W(i),a=hn(s.schema),c=oe(s,B()),l=eA(e),d=[],u=await _p({includeBody:l.has("history_drift"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let z=await np(i);z.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${z.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",m=FS(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=zS(m,f,s.validation.metadata_required_fields),h=MS(s),b=$S(e.dependencyCycleSeverity),v=jS(e.parentCycleSeverity),E=GS(e.scanMode),I=VS(i),A=await VA({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:I,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:h,dependencyCycleSeverity:b,parentCycleSeverity:v,fileScanMode:E,initialWarnings:[...new Set(d)]}),O=r?await WA(e,A,s,o,t,n):void 0,Q=[...new Set(A.warnings)].sort((z,pe)=>z.localeCompare(pe)),fe={ok:!A.checks.some(z=>z.status==="error"),has_warnings:Q.length>0,checks:A.checks,warnings:Q,...O!==void 0?{fixes:O}:{},generated_at:F(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?fe:{...PS(fe),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 KA(e,t){let n=e.dryRun===!0,r=await rn(process.cwd(),{includeLossless:!0}),{pendingDecisions:o}=jr(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.`,g.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(v=>v.field).join(", ")}.`),recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r.reduce((b,v)=>((b[v.item_id]??=[]).push(v),b),{}),s=Object.fromEntries(Object.entries(i).map(([b,v])=>[b,{merge:{receipts:v.map(Rt)}}])),a=await Nd({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=>Ts(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,v)=>{let E=l[v];if(b.status==="fulfilled"){let I=b.value.changed?"repaired":"skipped_clean";a.streams.push({id:E,outcome:I,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[I]+=1}else a.streams.push({id:E,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=>Wi(process.cwd(),b))),u=r.length);let f=await Ip({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),m=f.checks.every(b=>b.status==="ok"),_=a.totals.failed===0&&m,h=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(Rt)},validation:f,guidance:h,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{nl as ITEM_LATEST_TIMESTAMP_FIELDS,tl as ITEM_UNION_COLLECTION_FIELDS,is as MERGE_DRIVER_ARTIFACT_VALUES,cs as PM_GITATTRIBUTES_END,Pn as PM_GITATTRIBUTES_START,Wr as PM_GITATTRIBUTES_V2_END,Mt as PM_GITATTRIBUTES_V2_START,ds as auditMergeAttributeFence,us as auditMergeDriverConfiguration,Yr as buildMergeAttributePatterns,on as findGitWorkspaceRoot,jw as installMergeFence,rn as listMergeReceipts,Wi as markMergeReceiptReconciled,zi as mergeHistoryStreams,Bi as mergeItemDocuments,Gi as mergeJsonDocuments,qi as mergeRelationshipEventStreams,Fw as refreshMergeAttributeFenceIfInstalled,Bl as resolveMergeInstallContext,Xr as resolveProjectMergeTypeFolders,Cw as runMergeDriver,$w as runMergeInstall,By as runMergeReceiptReport,KA as runMergeReconcile,Rt as summarizeMergeReceipt};
|
|
106
|
+
`)}function ak(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 pu(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 ck(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 lk(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 dk(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=lk(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} ${fn} to read piped stdin input.`}function uk(e){let t=fu(e).trim();if(t.length===0||!t.includes(`
|
|
107
|
+
`)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=Ds(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]=pu(s[3].trim()),r=a;continue}if(r&&uu.has(r.toLowerCase())){n[r]=`${n[r]}
|
|
109
|
+
${i}`;continue}return null}return n}function pn(e,t){let n=fu(e).trim();if(!n)throw new y(`${t} cannot be empty`,h.USAGE);let r=uk(n);if(r)return r;let o={},i,s=ak(n);for(let a of s){let c=ck(a);if(c>0){let l=a.slice(0,c).trim(),d=pu(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&uu.has(i.toLowerCase())){o[i]=`${o[i]},${a.trim()}`;continue}throw new y(dk(e,t),h.USAGE)}return o}var fk=/^[A-Za-z]:[\\/]/,pk=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Ls(e){let t=e.trim();return fk.test(t)?!1:pk.test(t)}function mn(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 mk(e){if(process.stdin.isTTY===!0)throw new y(`${e} value "${fn}" 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(Ds(r))}),process.stdin.on("error",o=>{n(o)})})}function Ps(){let e,t,n=async i=>{if(t&&t!==i)throw new y(`Only one option may use "${fn}" stdin token per command invocation. Already used by ${t}.`,h.USAGE);return t=i,e||(e=mk(i)),await e};return{resolveValue:async(i,s)=>{if(i!==void 0)return i.trim()!==fn?i:await n(s)},resolveList:async(i,s)=>{if(!i)return;let a=i.map((d,u)=>d.trim()===fn?u:-1).filter(d=>d>=0);if(a.length===0)return i;if(a.length>1)throw new y(`${s} accepts "${fn}" stdin token at most once per command invocation`,h.USAGE);let c=await n(s),l=[...i];return l[a[0]]=c,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]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var _k={critical:0,high:1,medium:2,low:3,minimal:4},gk=Object.keys(_k),i$=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${gk.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 v$=new Map(Fo.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 Mk}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 Fk=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Cj=new RegExp(`\\b(${Fk.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var Ij=Mk(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 Nj=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]="ffe56aed-b794-5bf4-99fd-e3c5fe065163")}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 jk=[{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"}],qj=new Map(jk.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 Xj=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 Ms(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 l1 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 qk from"node:crypto";import Fs 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 T1=Fs.join("runtime","telemetry","events.jsonl"),S1=Fs.join("runtime","telemetry","state.json"),A1=Fs.join("runtime","telemetry","otel-spans.jsonl");var x1=3600*1e3;var C1=globalThis.fetch,Bk=["user","automation","test","dogfood"],I1=Promise.resolve(),O1=Promise.resolve();var R1=new Set(Bk);var N1=qk.randomUUID();var wu="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",D1=new RegExp(`\\b(${wu})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),L1=new RegExp(`(--${wu})(=|\\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]="a678b9f8-ba36-5127-877f-96bb4acc38c5")}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]="940f11a8-f40d-5169-ba74-e91920d32c4a")}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]="3b9b9ebe-8d98-5983-8257-b7b77c7e6194")}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]="f7e87e15-b5f3-53ab-86e2-768e94d5d329")}catch{}})();var $s=[{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"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"test",keys:["test"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],Eu=$s.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),vu=$s.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),js=[{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 dependencies by id or id=<id>,kind=<value>,source_kind=<value> selectors (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"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"test",keys:["test"],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},{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}],Us=js.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),ku=js.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]="e2028eff-b29e-5850-87b1-4a3e06f28964")}catch{}})();function re(e){return e.map(t=>({...t}))}var zs=[{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"}],Tu=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],Jk=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Tu],Su=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],Qk=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],Zk=[...zs,...Su],Au=[{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"}],eT=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],xu=[{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"}],qs=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...re(zs),...re(Jk),{param:"ids",flag:"--ids"},...re(Su),...re(eT),...re(Au),...re(xu),{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"}],Bs=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...re(Zk)],Gs=[{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"},...re(zs),...re(Tu),...re(Qk),...re(Au),...re(xu),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Cu=[{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"}],ho=re(Cu),Iu=[{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"}],Vs=re(Iu),Ou=[{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"}],Hs=re(Ou),Ws=[{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"}],Ks=re(Ws),Ys=re(Ws);var Xs=[{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}],Js=[{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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function Qs(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]="c82d9b50-274f-585d-be0e-9a0c5067b9e9")}catch{}})();var Ru=oi.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),tT=[...Ru,{flag:"--version"}],Nu=[{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"}],Du=[{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"}],Lu=ra([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{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:"--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"},...Nu,{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"])),Pu=[{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}],Mu=[{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 ra(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var Fu=[{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"}],$u=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ju=[{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"}],Uu=[{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"}],zu=[{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"}],qu=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],Bu=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Gu=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Vu=[{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"}],Hu=[{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"}],Wu=[{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"}],Ku=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Yu=[{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"}],Xu=[{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"}],Ju=[{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"}],oa=[{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"}],Ye=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],Qu=[...Ye,{flag:"--capability"}],Zs=[...oa,{flag:"--declarative"}],nT=[...Qu,{flag:"--declarative"}];var rT=[...Ye,{flag:"--markdown"},{flag:"--output"}];var oT=[...Ye,{flag:"--dry-run"}],iT=[...Ye,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],sT=[...Ye,{flag:"--watch"}],aT=[...Ye,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],cT=[...Ye,{flag:"--fields",list:!0}],lT=[...Ye,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Zu=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],ef=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var tf=[{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"}],nf=[{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"},...Du,{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"}],rf=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],of=[{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"]}],sf=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],af=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],cf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],lf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],df=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],uf=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],ff=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],ia=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...ff],pf=ia,mf=[{flag:"--at"},{flag:"--text"},...ff],_f=[{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:"--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"}],gf=[{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:"--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"}],hf=[{flag:"--limit"}],yf=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],bf=[{flag:"--dry-run"},{flag:"--scope"}],wf=[{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"}],Ef=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],vf=[{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"}],kf=[{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"}],Tf=[{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"}],Sf=[{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"}],Af=[{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"}],xf=[{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"]}],ea=[{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"},...Sf,...Af,{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"},{flag:"--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"}],Cf=[{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"}],If=[{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"}],Of=[{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"}],Rf=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Nf=[{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"},...xf,...Sf,{flag:"--fixed_version"},...Af,{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"},{flag:"--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"}],Df=[{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"},...Du,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...xf,{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"}],ta=[{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"}],Lf=[{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"}],Pf=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{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"}],na=ra([{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"])),Mf=[{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"}],Ff=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],$f=[{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}],jf=[{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"}],Uf=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],ft=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],zf=[{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"]}],qf=ra([{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"},...Nu],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),Bf=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Gf=[{flag:"--eager-tags"}];var dT=["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],EB=new Map([...dT.map(e=>[e,Lu]),["templates",ea],["cal",ta],["ctx",na],["test-runs-worker",yf],["init",Xu],["config",Ju],["extension",oa],["package",Zs],["packages",Zs],["install",Zu],["upgrade",ef],["create",ea],["item mutate",Cf],["item complete",If],["copy",Of],["focus",Rf],["aggregate",Pu],["calendar",ta],["context",na],["get",Mf],["guide",Ff],["search",qf],["next",zf],["eval",Uf],["workspace",ft],["workspace snapshot",ft],["workspace snapshot create",ft],["workspace snapshot list",ft],["workspace snapshot inspect",ft],["workspace snapshot restore",ft],["workspace snapshot delete",ft],["history",zu],["history-redact",Bu],["history-repair",Gu],["history-author-acknowledge",Vu],["history-compact",Hu],["merge",qu],["schema",Wu],["profile",Ku],["plan",Yu],["activity",Lf],["events",Pf],["restore",sf],["update",Nf],["update-many",Df],["close",tf],["close-many",nf],["delete",af],["append",rf],["comments",Mu],["notes",Fu],["learnings",$u],["files",ju],["docs",Uu],["deps",$f],["graph",jf],["test",_f],["test-all",gf],["telemetry",hf],["health",vf],["assurance",Tf],["validate",kf],["gc",bf],["stats",wf],["duplicates",Ef],["contracts",Bf],["completion",Gf],["claim",of],["release",cf],["start-task",lf],["pause-task",df],["close-task",uf],["meet",ia],["event",pf],["remind",mf]]);(function(){try{var e=typeof window<"u"?window:typeof 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 Vf={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Hf={if:{required:["field"]}};Reflect.set(Hf,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var Wf={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:[Hf],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:Vf,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:Vf,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]="4749819e-f2af-5a17-9d32-2e2770c497c3")}catch{}})();var Hn={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:Mr,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"},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"},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"}},Kf={assurance:{definition:Wf,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"}}]}},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}}},uT=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],sa={subcommand:{type:"string",enum:[...uT]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...xa]},mode:{type:"string",enum:[...Aa]},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:[...ar]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...Ca]},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"}}]}},aa={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"]}},Wn={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."},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"]}},Yf={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]}},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]="1d6089b2-ab59-59ad-a475-9a6ef1356b40")}catch{}})();var pT=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],mT=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],_T=new Set(["action","cwd","options",...Object.keys(Hn).filter(e=>e!=="severity")]);var gT={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},ep=["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"],PB=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(en.filter(e=>e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function be(e){return Qs(e)}var hT=be([...Vs.map(e=>e.param),...ho.map(e=>e.param),"assignee","closeReason","completedAt"]),tp=be([...Hs.map(e=>e.param),...ho.map(e=>e.param),"force"]),yT=be([...Ks.map(e=>e.param),...tp.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),bT=be([...Ys.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),Xf=be([...Js.map(e=>e.param),"past","section"]),wT=be([...Xs.map(e=>e.param),"stream"]),pt=be([...qs.map(e=>e.param),"includeBody","noTruncate","strictRead","compact","brief","full"]),mt=[[{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"}}]],ET=[[{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}}]],vT=be([...Bs.map(e=>e.param),"count","completion","includeUnparented"]),kT=be(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Gs.map(e=>e.param)]),Jf=be(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),de=["author","message","force"],np=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],Kn=["author","assignee","message","force"],TT=["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 Qf(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:TT}}}var Zf={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},yo={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"]},...Qf("extension"),...Qf("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:hT},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:pt,mutuallyExclusiveWhen:mt},"list-all":{optional:pt,mutuallyExclusiveWhen:mt},"list-draft":{optional:pt,mutuallyExclusiveWhen:mt},"list-open":{optional:pt,mutuallyExclusiveWhen:mt},"list-in-progress":{optional:pt,mutuallyExclusiveWhen:mt},"list-blocked":{optional:pt,mutuallyExclusiveWhen:mt},"list-closed":{optional:pt,mutuallyExclusiveWhen:mt},"list-canceled":{optional:pt,mutuallyExclusiveWhen:mt},aggregate:{optional:vT},guide:{optional:["list","format","depth"]},context:{optional:Xf},ctx:{optional:Xf},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:kT,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter"]},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:Zf,event:Zf,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...Jf,"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",...de],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...de],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",...de]},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",...ep,"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",...de]},activity:{optional:wT},restore:{required:["id","target"],optional:de},update:{required:["id"],optional:tp,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:yT,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...np,...de]},"close-many":{optional:bT},delete:{required:["id"],optional:["dryRun",...de]},append:{required:["id","body"],optional:de},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...de]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full",...de],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full",...de]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...de],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...de],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","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...de]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","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:ET},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...Jf,...Kn],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:Kn},"start-task":{required:["id"],optional:Kn},"pause-task":{required:["id"],optional:Kn},"close-task":{required:["id"],optional:["text","validateClose",...Kn]}},ST=Object.freeze(Object.fromEntries(en.map(e=>[e,yo[e]])));function rp(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function AT(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=Wn[e];return{...n,description:r?.description??rp(e),...r?.examples?{examples:r.examples}:{}}}function xT(e,t){if(e==="plan"&&Object.prototype.hasOwnProperty.call(aa,t))return aa[t];let n=Yf[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:Wn[t]}function CT(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=xT(e,t);return{...r,description:o?.description??rp(t),...o?.examples?{examples:o.examples}:{}}}function IT(e,t){let n=Kf[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(sa,t)?sa[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:Hn[t]}function OT(e,t){let n={action:{const:e,description:Wn.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=IT(e,r);o&&(n[r]=CT(e,r,o))}return n}function RT(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 NT(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:be(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 op(e){if(!Object.prototype.hasOwnProperty.call(yo,e))return;let t=yo[e],n=gT[e]??[];return be(["action",...pT,...Pr(e)!==void 0?mT:[],...n,...t.required??[],...t.optional??[]])}function DT(e){let t=yo[e],n=be(t.required??[]),r=op(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:OT(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=RT(e,t.oneOfRequired));let i=NT(t);return i.length>0&&(o.allOf=i),o}function ip(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 ca="4.7.0",sp=ca.split(".")[0],ap="1.3.0",LT=ip(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${sp}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":ca,type:"object",oneOf:en.map(e=>DT(e))}));function PT(e,t){let n=AT(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 MT(){let e={action:{type:"string",description:Wn.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(Hn).sort())e[t]=PT(t,Hn[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":ap,type:"object",additionalProperties:!1,required:["action"],properties:e}}var FT=ip(MT);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b227cb2-a30d-5384-b9c2-558603181c67")}catch{}})();var zB=new Set([...Hc,...Wc]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="969b5bd2-e7de-5db8-bef2-6748675a100c")}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]="8d60b13c-c58a-506f-adc9-2414dd69edef")}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]="0e153ece-4fc0-5134-97f0-c2315aff0031")}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]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var WT="2026-07-15T06:22:12.276Z",KT=Date.parse(WT),YT=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],cp=e=>typeof e=="string"?e:"",XT=e=>{let t=e??{},n=cp(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(cp(t.ts))>=KT);return YT[r][o]};function JT(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=XT(_);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 QT(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 lp=async(e,t=20,n=!1)=>{let r=da.join(e,"history"),o;try{o=(await la.readdir(r)).filter(E=>E.endsWith(".jsonl")).sort((E,v)=>E.localeCompare(v))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,_="_workspace.jsonl",g=new Set;if(o.includes(_))try{g=QT(await la.readFile(da.join(r,_),"utf8"))}catch{g=new Set}for(let E of o){let v;try{v=await la.readFile(da.join(r,E),"utf8")}catch{continue}let C=E.slice(0,-6),A=JT(C,v,t-s.length,g,n);c+=1,l+=A.checked_events,d+=A.unknown_event_count,u+=A.legacy_unknown_event_count,f+=A.actionable_unknown_event_count,p+=A.acknowledged_actionable_event_count,A.unknown_event_count>0&&i.add(C),s.push(...A.samples),n&&a.push(...A.actionable_events)}let b=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...i].sort((E,v)=>E.localeCompare(v)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import ZT from"node:fs/promises";import Se from"node:path";import eS 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]="72f57c4d-65c5-57f1-a16a-f6c970aca680")}catch{}})();var tS=["path","scope","note"],nS=["pattern","glob","path","scope","note"],rS=["path"],oS=["from","to"],iS=new Set(["note","scope"]);function up(e){let t=e??"project";if(!$o.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${$o.join(", ")} (default: project).`,h.USAGE);return t}function fa(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("=")||Ls(e)}function sS(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||fa(n)||!n.includes(",")?[t]:Ms(n)})}function aS(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function cS(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!fa(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&&aS(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 lS(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let o=cS(r);if(o!==void 0)return[o]}return sS([n]).map(o=>{let i=o.trim(),s=fa(i)?pn(o,"--add"):{path:i};if(mn(s,"--add",tS),!s.path)throw new y(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return{path:s.path,scope:up(s.scope),note:s.note?.trim()||void 0}})}):[]}function dS(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=pn(n,"--add-glob");mn(r,"--add-glob",nS);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:up(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function uS(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=pn(n,"--remove"),o=Object.keys(r).filter(i=>iS.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(mn(r,"--remove",rS),!r.path)throw new y("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function fS(e){return e?e.map(t=>{let n=pn(t,"--migrate");mn(n,"--migrate",oS);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 Yn(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 pS(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>Yn(i.path,n))),o=[...new Set(t.map(i=>Yn(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 bo(e){return e.split(Se.sep).join("/")}function ua(e,t,n=process.cwd()){let r=e.trim();if(Vn(r))return r;if(Se.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return bo(r.replaceAll("\\",Se.sep));let o=Se.relative(t,n);return o.startsWith(`..${Se.sep}`)||o===".."||Se.isAbsolute(o)?bo(Se.normalize(r)):bo(Se.relative(t,Se.resolve(n,r)))}async function mS(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=Se.isAbsolute(o.pattern),s=await eS(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>ua(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 _S(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 gS(e){return`${e.path}::${e.scope}`}function fp(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function pp(e){return[...new Map(e.map(t=>[gS(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function hS(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(Vn(a)){s.push(a.trim());continue}let c=Se.isAbsolute(a)?a:Se.resolve(t,a);try{(await ZT.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&Uo(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 yS(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=Yn(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=Yn(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>Yn(s,r)),count:o}}function bS(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=pp(e);return r?o:fp(o)}async function dp(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 hS(t,e.workspaceRoot):void 0}}async function wo(e,t,n,r){let{metadataKey:o}=r,i=Ps(),s=te(process.cwd(),n.path),a=ni(s),c=process.cwd();if(!await D(U(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,h.NOT_FOUND);let l=await W(s),d=oe(l,B()),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=lS(u,r.bareNoun).map(q=>({...q,path:ua(q.path,a,c)})),b=dS(f),E=await mS(b,a,c),v=_S([...g,...E],t.note,g.length>0||b.length>0),C=uS(p).map(q=>ua(q,a,c)),A=fS(_);if(pS(v,C,A),!(v.length>0||C.length>0||A.length>0)){let q=await Le(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!q)throw new y(`Item ${e} not found`,h.NOT_FOUND);let K=(await Te(q,{schema:l.schema})).document.metadata[o]??[];return dp({id:q.id,artifacts:K,changed:!1,options:t,workspaceRoot:a})}let Q=Oe(t.author,l.author_default),$=await _o({pmRoot:s,settings:l,id:e,op:r.op,author:Q,message:t.message,force:t.force,skipNoop:!0,mutate(q){let I=q.metadata,K=I[o]??[],ba=[...K],Jn=yS(ba,v,C,A),xo=bS(ba,Jn.adds,Jn.removes,r.supportsAppendStable&&t.appendStable===!0);xo.length>0?I[o]=xo:delete I[o];let wa=!Ee(K,xo);return{changedFields:wa?[o]:[],warnings:wa&&Jn.count>0?[`path_migrations_applied:${Jn.count}`]:[]}}}),fe=$.item[o]??[],z=$.warnings.find(q=>q.startsWith("path_migrations_applied:")),pe=z?Number(z.slice(24)):0;return dp({id:$.item.id,artifacts:fe,changed:$.changedFields.includes(o),migrationsApplied:pe,options:t,workspaceRoot:a})}function Eo(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 mp(e,t,n){let r=await wo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Eo(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]="515cd35c-8e0e-51d4-8ad9-1cea5be8a572")}catch{}})();async function _p(e,t,n){let r=await wo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Eo(r,"files")}import{readFileSync as wS}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 ES=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),yp=new Set(["--pm-path","--path","--author"]),vS={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"])},kS=new Set(["-p","--package"]),TS=new Set(["-c","--call"]),SS=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),AS=new Set(["-C","--prefix","--userconfig","--cache"]);var xS=new Set(["exec","x"]);function CS(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function IS(e,t=process.cwd()){let n=OS(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(gp(r)||hp(r,t))return o;if(r==="node"&&o[0]&&hp(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?pa(o):r==="pnpm"?DS(o):r==="npm"?LS(o):null;return i&&(gp(i.command)||NS(i.command))?i.args:null}var bp=(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 CS(i)){let c=IS(a),l=c?PS(c):null,d=l&&ES.has(l.subcommand)?MS(l.remaining,vS[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 OS(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 gp(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function RS(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 NS(e){let t=RS(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function hp(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(wS(vo.join(vo.dirname(vo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function pa(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(TS.has(r)){t+=1;break}t+=kS.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function wp(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 DS(e){let t=wp(e,SS);return t?.subcommand!=="dlx"?null:pa(t.args)}function LS(e){let t=wp(e,AS);return!t||!xS.has(t.subcommand)?null:pa(t.args)}function PS(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(yp.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function MS(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("=")&&(yp.has(r)||t.has(r))&&(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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Ep(e){return e.includeBody?mo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):qn(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 FS=5;async function vp(e,t,n){let r=await go(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:FS,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]="b8c4707f-5445-5079-96e5-dc0dbd649b34")}catch{}})();var zS=["src","tests","docs"],qS=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],BS=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),GS=["resolution","expected_result","actual_result"],VS=["default","tracked-all","tracked-all-strict"],kp=["core","strict","custom"],To=["off","warn","error"];var _a=["author","acceptance_criteria","estimated_minutes","close_reason"],Ip=[..._a,"reviewer","risk","confidence","sprint","release"],ya=Array.from(new Set(Ip)),HS={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"},WS={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"},KS={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"},YS={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"},XS={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"},JS=32*1024*1024,QS=1e4,Op=40,ht=5,ZS=4096,eA=255,tA=US(jS);function Rp(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Rp(r):r);return t}function nA(e){return{...e,checks:e.checks.map(t=>({...t,details:Rp(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 jt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Tp(e){return jt(e).replace(/\/+$/,"")}function ze(e){let t=se(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ao(e,t){return vt(e,t)??e}function Xn(e,t){return t.terminal_statuses.has(Ao(e,t))}function _t(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ko(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function rA(e){let t=_t(Po),n={blocked_reason:_t(yt.blocked_reason),resolution:_t(yt.resolution),actual_result:_t(yt.actual_result)},r=_t(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:_t(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:_t(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:_t(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ko(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:ko(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ko(o.resolution,n.resolution)?"default":"settings",actual_result:ko(o.actual_result,n.actual_result)?"default":"settings"}}}function oA(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(kp.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${kp.join(", ")}.`,h.USAGE)}function iA(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(To.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${To.join(", ")}.`,h.USAGE)}function sA(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(To.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${To.join(", ")}.`,h.USAGE)}function aA(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>HS[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function cA(e,t,n){let r=aA(n);return e==="core"?{profile:e,profile_source:t,required_fields:[..._a],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Ip],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:[..._a],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var lA=new Set(["acceptance_criteria","estimated_minutes"]);function dA(e,t,n,r){return!r&&lA.has(t)&&Xn(e.status,n)?!1:t==="author"?!se(e.author):t==="acceptance_criteria"?!se(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ao(e.status,n)===n.close_status&&!se(e.close_reason):t==="reviewer"?!se(e.reviewer):t==="risk"?!se(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!se(e.confidence):t==="sprint"?!se(e.sprint):!se(e.release)}function uA(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: ${VS.join(", ")}.`,h.USAGE)}function fA(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return ue.resolve(t);let n=ue.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return ue.dirname(ue.dirname(n));let o=ue.resolve(process.cwd()),i=Sp(n),s=Sp(o),a=ue.relative(i,s);return a.length===0||!a.startsWith("..")&&!ue.isAbsolute(a)?n:o}function Sp(e){try{return $S.native(e)}catch{return ue.resolve(e)}}function pA(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Np(e,t,n){let r=t.length>0?ue.join(e,t):e,o;try{o=await ha.readdir(r,{withFileTypes:!0})}catch(i){if(X(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?ue.join(t,i.name):i.name;if(i.isDirectory()){if(BS.has(i.name))continue;await Np(e,s,n);continue}i.isFile()&&n.push(jt(s))}}async function Ap(e){let t=[];for(let n of zS)await Np(e,n,t);for(let n of qS){let r=ue.join(e,n);try{(await ha.stat(r)).isFile()&&t.push(jt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function mA(e){try{let{stdout:t}=await tA("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:JS,windowsHide:!0,timeout:QS}),n=t.split("\0").map(r=>jt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function _A(e,t){let n=new Set,r=Tp(Ut);r.length>0&&n.add(r);let o=Tp(ue.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function xp(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function gA(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await mA(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await Ap(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await Ap(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function J(e,t=ht){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function gt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=J(e,Op);return{values:n.values,truncated:n.truncated,total:e.length}}var hA={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},yA={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function bA(e){let t=e.missing_fields.map(n=>`${hA[n]} "${yA[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function wA(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"):Ud(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 EA(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 vA="validate_metadata_duplicate_issue_codes";function kA(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ht,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:[`${vA}:${e.length}`]}}function TA(){return Object.fromEntries(ya.map(e=>[e,[]]))}function SA(e,t,n){let r=TA();for(let o of e)for(let i of ya)dA(o,i,t,n)&&r[i].push(o.id);return r}function AA(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${WS[o]}:${i.length}`)}return r.push(...n),r}function xA(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=KS[r];n[s]=i}return n}function CA(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 IA(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=YS[o],a=XS[o];if(!s||!a)continue;let c=J(i,r?i.length:ht);e[s]=c.values,e[a]=c.truncated}}function OA(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:se(n.get(o)?.resolution)})):[]}function RA(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:se(n.get(o)?.type)})):[]}function NA(e,t,n,r){let o=new Map(e.map(b=>[b.id,b])),i=t.profile==="strict",s=SA(e,n,i),a=Xd(e),c=kA(a,r),l=AA(t,s,c.warnings),d=xA(t,s),u=CA(t,s,o),f=Jd(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:[...ya],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]),IA(p,t,s,r);let _=OA(t,s,o),g=RA(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 DA(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(Ao(f.status,t))),i=[],s=[];for(let f of o){let p=GS.filter(_=>!se(f[_]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:se(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:ht,l=J(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>bA(f)),u=J(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 LA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PA(e,t="pm",n=Qt()){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=ze(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=ze(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>ze(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=ze(i.definition_of_ready);return FA(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function MA(e,t,n){let r=su(e,n?d=>Xn(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:ht,a=J(o,s),c=J(i,s),l=J(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 FA(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${LA(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 Dp(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 Lp(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=>{let c=(t.get(a)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&o.length>1)return o.push(n),!0;if(!i.has(l)){if(i.add(l),o.push(l),s(l))return!0;o.pop(),i.delete(l)}}return!1};return s(n)?[...o]:[...e,n]}function $A(e,t="pm"){let n=PA(e,t),r=Dp(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>Lp(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function jA(e,t=Qt()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));return[...e].sort((i,s)=>i.id.localeCompare(s.id)).forEach(i=>{let s=r.get(i.id),a=ze(i.parent),c=a?n.get(a.toLowerCase()):void 0;c&&s.push(c),(i.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?r.get(u).push(i.id):s.push(u))})}),r.forEach((i,s)=>{r.set(s,[...new Set(i)].sort((a,c)=>a.localeCompare(c)))}),r}function UA(e){let t=jA(e),n=Dp(t),r=[...new Set(n.flat())].sort((i,s)=>i.localeCompare(s)),o=n.map(i=>Lp(i,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:o}}function zA(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 So(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function qA(e,t){let n=So(e).split("/").filter(Boolean),r=So(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function BA(e,t){let n=So(t),r=So(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=qA(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 GA(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function VA(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=jt(s.path);if(a.length===0||a===e)return;let c=BA(e,a);c!==null&&GA(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 HA(e,t){return e.map(n=>{let r=zA(n),o=r==="docs_unowned"?"docs":"files",i=VA(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 WA(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function KA(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=ze(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function YA(e,t,n,r,o){let i=ze(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&&!Xn(s.status,o)}}function XA(e,t,n,r){let o=ze(e.blocked_by),i=ze(e.blocked_reason),s=i?.toLowerCase(),a=Ao(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 JA(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=>!Xn(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=KA(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=ze(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&Xn(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(YA(c,u,o,i,n))),t){let f=XA(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 QA(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 Cp(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ZA(e,t,n,r,o,i){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Cp("validate_lifecycle_dependency_cycles",n,o),c=Cp("validate_hierarchy_parent_cycle",r,i);return[...s,...a?[a]:[],...c?[c]:[]]}function ex(e){let t=jt(e);return t.length>ZS||t.split(/[\\/]/).some(n=>n.length>eA)}async function tx(e,t){let n=ue.isAbsolute(t)?t:ue.resolve(e,t);if(ex(n))return!1;try{let r=await ha.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return pA(r,["ENOENT","ENOTDIR"])}}async function nx(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(Vn(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=jt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await tx(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function rx(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:_A(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>xp(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!xp(p,l)),f={};if(d.length>0){let p=gt(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 ox(e,t,n,r,o,i,s,a="pm"){let c=JA(e,t,o,i);QA(c);let l=$A(c.activeItems,a),d=UA(e),u=ZA(c,t,n,r,l.cycle_count,d.cycle_count),f=s?Number.POSITIVE_INFINITY:ht,p=J(c.closureLikeRows.map(O=>`${O.id}:${O.fields.join(",")}`),f),_=J(c.terminalParentRows.map(O=>`${O.id}:${O.parent_id}:${O.parent_status}`),f),g=J(c.staleBlockerRows.map(O=>`${O.id}:${O.status}:${O.reasons.join(",")}`),f),b=J(l.cycle_item_ids,f),E=J(l.cycle_sample_paths,f),v=J(d.cycle_item_ids,f),C=J(d.cycle_sample_paths,f),A=l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="error";return{check:{name:"lifecycle",status:A?"error":u.length===0?"ok":"warn",ok:!A&&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:E.values,dependency_cycle_sample_paths_truncated:E.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:C.values,parent_cycle_sample_paths_truncated:C.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 ix(e,t,n,r,o,i){let s=await nx(e,t),a=new Map(e.map(I=>[I.id,I])),c=[...new Set(s.missingLinkedPaths)].sort((I,K)=>I.localeCompare(K)),l=await gA(t,r),d=rx(l,n,t,r,o,i),u=d.candidateFiles.filter(I=>!s.linkedProjectPaths.has(I)),f=HA(u,e),p=eu(c,d.candidateFiles),_=new Map(p.map(I=>[I.path,I.classification])),g=p.filter(I=>I.classification==="moved").length,b=s.staleLinkRows.map(I=>({...I,classification:_.get(I.path)??"deleted"})).sort((I,K)=>I.item_id.localeCompare(K.item_id)||I.path.localeCompare(K.path)||I.link_kind.localeCompare(K.link_kind)),E=[];d.strictModeForcesPmInternals&&E.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&E.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&E.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((I,K)=>I.localeCompare(K)),C=gt(v,i),A=gt(c,i),O=gt(u,i),Q=gt(f.map(I=>`${I.path}:${I.classification}:owner_candidate=${I.owner_candidate?.id??"unowned"}`),i),$=i?f:gt(WA(f),!1).values,fe=gt(tu(p),i),z=b.map(I=>({item_id:I.item_id,path:I.path,link_kind:I.link_kind,classification:I.classification})),pe=ru(z,I=>{let K=a.get(I);return K?{type:K.type,title:K.title,status:K.status}:void 0}),q=i?pe:gt(ou(pe),!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:Op,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:o,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:A.total,missing_linked_paths:A.values,missing_linked_paths_truncated:A.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:fe.values,missing_linked_path_classifications_truncated:fe.truncated,missing_linked_path_rows_count:pe.length,missing_linked_path_rows:q,orphaned_paths_count:u.length,orphaned_paths_total:O.total,orphaned_paths:O.values,orphaned_paths_truncated:O.truncated,orphaned_path_classifications:Q.values,orphaned_path_classifications_truncated:Q.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:$}},warnings:E,staleLinkPruneRows:b}}function sx(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),o=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${o}`}function ax(e,t,n){let r=new Set(e.map(b=>b.id.toLowerCase())),o=0,i=0,s=new Set,a=[],c=e.flatMap(b=>(b.tests??[]).map(E=>({item:b,linkedTest:E})));for(let{item:b,linkedTest:E}of c){if(typeof E.command!="string"||E.command.trim().length===0)continue;o+=1;let v=bp(E.command,t);if(v.length!==0){i+=v.length;for(let C of v)s.add(C),r.has(C.toLowerCase())||a.push(sx(b.id,C,E.command))}}let l=[...new Set(a)].sort((b,E)=>b.localeCompare(E)),d=[...new Set(l.map(b=>b.split(":")[1]??""))].filter(b=>b.length>0).sort((b,E)=>b.localeCompare(E)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],f=n?Number.POSITIVE_INFINITY:ht,p=J(l,f),_=J(d,f),g=J([...s].sort((b,E)=>b.localeCompare(E)),f);return{check:{name:"command_references",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:e.length,linked_commands_scanned:o,referenced_pm_ids_count:i,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:g.values,unique_referenced_pm_ids_truncated:g.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:_.values,stale_pm_ids_truncated:_.truncated,stale_pm_id_reference_rows:p.values,stale_pm_id_reference_rows_truncated:p.truncated}},warnings:u}}function cx(e,t){let n=Ka(e.map(c=>({ref:c.id,version:Ha(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:ht,i=J(n.outdated,o),s=J(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:gr,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 ga="pm validate auto-fix";async function lx(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:ga};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 ma(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function dx(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>ma(a)===null))try{await lx(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>ma(a)!==null)){let a=ma(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 _p(a.item_id,{remove:c,message:ga},t):await mp(a.item_id,{remove:c,message:ga},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}async function ux(e,t,n,r){let o=await cu(e,new Set(t.map(g=>g.id)),n,{schema:r.schema,extensionFieldNames:We(B())}),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 du(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ms(e,eo(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await sn(e),d=l===null?null:await _s(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 on(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:f,lossless:p}=Br(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:p.length,lossless_merge_receipt_items:[...new Set(p.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 Xe(e,t,n){n&&wA(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function fx(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=NA(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,Xe(t,o,n)}if(e.requestedChecks.has("resolution")){let o=DA(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,Xe(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=ox(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,Xe(t,o,n),Xe(t,MA(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await ix(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,Xe(t,o,n)}return e.requestedChecks.has("command_references")&&Xe(t,ax(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&Xe(t,await vp(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&Xe(t,cx(e.items,r),n),e.requestedChecks.has("storage_integrity")&&Xe(t,await ux(e.pmRoot,e.items,oe(e.settings,B()).type_to_folder,e.settings),n),t}function px(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Bd(t.closeReasonBackfillRows)),r.push(...qd(t.resolutionBackfillRows)),r.push(...Gd(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...Vd(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...Hd(t.staleLinkPruneRows)),r}async function mx(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=px(e,t,n),{applicable:a,gated:c}=Kd(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await dx(a,o,i);d.push(...f.applied.map(Gn)),u.push(...f.failed.map(({fix:p,error:_})=>({...Gn(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(Gn),applied_fixes:d,gated_fixes:c.map(f=>({...Gn(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function Pp(e,t,n={}){Lc(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=Wd(e.fixScope),i=te(process.cwd(),t.path);if(!await D(U(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,h.NOT_FOUND);let s=await W(i),a=yn(s.schema),c=oe(s,B()),l=EA(e),d=[],u=await Ep({includeBody:l.has("history_drift"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let z=await lp(i);z.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${z.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=oA(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=cA(p,f,s.validation.metadata_required_fields),g=rA(s),b=iA(e.dependencyCycleSeverity),E=sA(e.parentCycleSeverity),v=uA(e.scanMode),C=fA(i),A=await fx({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:C,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:g,dependencyCycleSeverity:b,parentCycleSeverity:E,fileScanMode:v,initialWarnings:[...new Set(d)]}),O=r?await mx(e,A,s,o,t,n):void 0,Q=[...new Set(A.warnings)].sort((z,pe)=>z.localeCompare(pe)),fe={ok:!A.checks.some(z=>z.status==="error"),has_warnings:Q.length>0,checks:A.checks,warnings:Q,...O!==void 0?{fixes:O}:{},generated_at:F(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?fe:{...nA(fe),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 _x(e,t){let n=e.dryRun===!0,r=await on(process.cwd(),{includeLossless:!0}),{pendingDecisions:o}=Br(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(Nt)}}])),a=await jd({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=>Cs(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 v=l[E];if(b.status==="fulfilled"){let C=b.value.changed?"repaired":"skipped_clean";a.streams.push({id:v,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:v,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=>Ji(process.cwd(),b))),u=r.length);let f=await Pp({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),p=f.checks.every(b=>b.status==="ok"),_=a.totals.failed===0&&p,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(Nt)},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{ll as ITEM_LATEST_TIMESTAMP_FIELDS,cl as ITEM_UNION_COLLECTION_FIELDS,ls as MERGE_DRIVER_ARTIFACT_VALUES,fs as PM_GITATTRIBUTES_END,Mn as PM_GITATTRIBUTES_START,Jr as PM_GITATTRIBUTES_V2_END,Ft as PM_GITATTRIBUTES_V2_START,ms as auditMergeAttributeFence,_s as auditMergeDriverConfiguration,Zr as buildMergeAttributePatterns,sn as findGitWorkspaceRoot,oE as installMergeFence,on as listMergeReceipts,Ji as markMergeReceiptReconciled,Vi as mergeHistoryStreams,Wi as mergeItemDocuments,Ki as mergeJsonDocuments,Hi as mergeRelationshipEventStreams,nE as refreshMergeAttributeFenceIfInstalled,Xl as resolveMergeInstallContext,eo as resolveProjectMergeTypeFolders,Ww as runMergeDriver,rE as runMergeInstall,cb as runMergeReceiptReport,_x as runMergeReconcile,Nt as summarizeMergeReceipt};
|
|
111
111
|
//# sourceMappingURL=sdk-merge.js.map
|