@unbrained/pm-cli 2026.11.21 → 2026.11.22
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/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-PJXKA4QU.js → chunk-4TB5D6HL.js} +37 -37
- package/dist/cli-bundle/chunks/{chunk-WELSVDPU.js → chunk-5ZMVLWE3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
- package/dist/cli-bundle/chunks/{chunk-JVGRFU5H.js → chunk-AR4NP5HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XHJ3H5PL.js → chunk-B4PPFOPY.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-5647LU3A.js → chunk-B76TFRO2.js} +47 -45
- package/dist/cli-bundle/chunks/{chunk-YJEBK7HU.js → chunk-CAR2L5NW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D6ILFXZY.js → chunk-EIGUKEV6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XWHJIRNV.js → chunk-GTPCAJMZ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-CASX6SFI.js → chunk-HC2OPETM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NCFCBKIP.js → chunk-HKUV74K3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-S6HB3WL2.js → chunk-J2LABXBL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BKSVHOWI.js → chunk-J52BEBSS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NT5AKFE5.js → chunk-OJTMGDON.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-SRVTCYAU.js → chunk-TC6XLIYO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AHQB7W2H.js → chunk-U7EL3AYA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-CIKGG34F.js → chunk-X6MIWTTT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-RMIRNYRG.js → chunk-XFHPKXAE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6QLEXRUG.js → chunk-YHVLVSEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-4QBMZXKX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-3TG636XG.js → mutation-actor-FWLYWJ37.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-LICSDNNO.js → mutation-admission-7ZDCK3G2.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-RR5KACJ3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WWVECKFQ.js → register-mutation-57AJQWFV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-L6HFJNWD.js → register-operations-RKWST7CU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-K7UFG5TD.js → register-setup-CMI23PC5.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-57KH3KAC.js → stage-4KDVXC5Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YOAYY3HE.js → chunk-2ZD7275J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-532WZV65.js → chunk-324AHXJO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QGKLRXP7.js → chunk-4JZITIJB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CU2BRAOX.js → chunk-4KTFKSS3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MKM5NKD7.js → chunk-BRZV7BFV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RPE6IX26.js → chunk-HDEKFSOK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LNHUE4VV.js → chunk-IWOXAUDU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J63D6QST.js → chunk-ML3JHCC6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JMQJBZQ5.js → chunk-OPGOOP25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XCJSHNXK.js → chunk-RE7ZWT7D.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WXMI4AV5.js → chunk-RQ252B6V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7A4QWNZX.js → chunk-URGHTTT3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IQK5NPMG.js → chunk-USPYKWQG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-UOC6257J.js → chunk-WZWXGDYY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NP72ZDXE.js → chunk-YKSLZPLT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-2O6MLPEX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-actor-62HKR5IO.js → mutation-actor-TCYDPUGG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-X4PF2SG3.js → mutation-admission-LY73EJWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-O7T7CXBB.js → stage-DQ7RQQ52.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- 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 +70 -58
- 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 +11 -11
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/completion/fish.js +3 -2
- package/dist/sdk/completion/zsh.js +3 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +8 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +6 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +7 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +6 -2
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/README.md +2 -2
- package/docs/SDK.md +103 -4
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +30 -2
- 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/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
- package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
- package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
- package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
- package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/PERFORMANCE.md +0 -204
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import{A as y,C as nn,D as me,E as B,F as Pc,I as $c,J as Mc,a as fe,b as ei,c as Rc,e as er,f as tr,g as nr,h as Cc,i as rr,j as St,k as xc,m as ke,n as Nc,o as Dc,p as or,q as ir,t as tn,x as ti,z as g}from"./chunk-3IRCYJI5.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function sr(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 d=s[0];for(let l=1;l<=t.length;l+=1){let u=e[c-1]===t[l-1]?0:1,f=i[l-1]+u,m=s[l-1]+1,p=i[l]+1,h=Math.min(f,m,p);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(h=Math.min(h,o[l-2]+1)),s[l]=h,h<d&&(d=h)}if(d>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}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]="04a7faba-2e58-5fac-aa38-e24f218c339d")}catch{}})();var F_=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],jc=F_,kt=["draft","open","in_progress","blocked","closed","canceled"],Lc=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],ar=["string","number","boolean","string_array","array","object"],Fc=["create","update","update_many","list","search","calendar","context"],Uc=["allow","warn","reject"],fT=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],mT=["project","global"],pT=["low","medium","high","critical"],cr=["low","medium","high","critical"],dr=["low","medium","high"];var _T=["minimal","default","strict","custom"],hT=["none","warn","strict"],gT=["progressive","strict"],yT=["off","warn","strict"],bT=["off","warn","strict"],wT=["off","warn","strict"];var lr=["daily","weekly","monthly","yearly"],rn=["mon","tue","wed","thu","fri","sat","sun"];function ni(e){return rn.indexOf(e)}var vT=["draft","research","review","approved","executing","paused","completed","superseded"],zc=["pending","in_progress","completed","blocked","skipped","superseded"],ET=["codex","claude-code","cursor","generic"],OT=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],ST=["brief","standard","deep","full"],kT=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67511565-01f8-58a6-ad06-45b5d0ce831b")}catch{}})();var U_=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function z_(e){return{unknownKeys:Object.keys(e).filter(t=>!U_.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function H_(e){let t=z_(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function Hc(e,t,n){return H_(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var ri=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="418b3f7f-6350-5878-a362-3948de287baf")}catch{}})();function mr(e){return e.trim().toLowerCase().replaceAll("-","_")}function B_(e){if(e===void 0)return;let t=mr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function ii(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)ii(n,t);return Object.freeze(e)}for(let n of Object.values(e))ii(n,t);return Object.freeze(e)}function V_(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 q_(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 W_(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 G_(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=mr(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 K_(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function Y_(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function X_(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var si=class{#e=new Map;#n=new Map;constructor(t=ri){for(let n of t)this.register(n)}register(t){let n=G_(t);if(K_(t,n),Y_(t,n),V_(t,n),q_(t,n),W_(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=B_(t.inverse),o=[...new Set((t.aliases??[]).map(mr))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:X_(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?ii(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=mr(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function ai(){return new si}var qe=ai();function xT(e){return qe.require(e).kind}function NT(e){return qe.resolve(e)?.kind}function DT(e,t=qe){return t.resolve(e)?.ordering===!0}function J_(e,t,n,r=qe){let o=on(e),i=on(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function ur(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function Q_(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=J_(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function fr(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function on(e){return typeof e=="string"?e.trim():""}function oi(e,t){let n=on(e);return n&&t.has(n)?n:void 0}function Z_(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Bc=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=qe){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=Q_(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(ur));for(let i of this.#r)fr(this.#s,i.source,i),fr(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(fr(this.#s,i.target,i),fr(this.#a,i.source,i))}static fromItems(t,n=qe){let r=new Set(t.map(i=>on(i.id)).filter(Boolean)),o=[];for(let i of t){let s=on(i.id);if(!s)continue;let a=oi(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=oi(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=oi(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||ur(a,c)<=0?a:c;o.at(-1)!==d&&o.push(d),a===d&&(i+=1),c===d&&(s+=1)}return Object.freeze(o)}nodes(){return this.#o}hasNode(t){return this.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||ur(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=[...new Set(o.map(c=>c.id))],a=s.slice(0,i);return{value:a,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:a.length<s.length,nextCursor:a.at(-1)}}}neighborEdges(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=o.slice(0,i);return{value:s,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:s.length<o.length,nextCursor:s.at(-1)?.id}}}closure(t,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,u=0,f=!1;e:for(let m=0;m<d.length;m+=1){n.signal?.throwIfAborted();let p=d[m];l+=1;let h=this.#t(p.id,o,r);if(u+=h.length,p.depth>=s){h.some(_=>!a.has(_.id))&&(f=!0);continue}for(let _ of h)if(!a.has(_.id)){if(c.length>=i){f=!0;break e}a.add(_.id),c.push(_.id),d.push({id:_.id,depth:p.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:u,truncated:f,nextCursor:c.at(-1)}}}shortestPath(t,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,u=0,f=!1;for(let m=0;m<a.length;m+=1){r.signal?.throwIfAborted();let p=a[m];l+=1;let h=this.#t(p.id,i,o);if(u+=h.length,p.depth>=s){h.some(_=>!d.has(_.id))&&(f=!0);continue}for(let _ of h)if(!d.has(_.id)){if(c.set(_.id,p.id),_.id===n)return{value:Z_(t,n,c),meta:{visitedNodes:l,inspectedEdges:u,truncated:!1}};d.add(_.id),a.push({id:_.id,depth:p.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:u,truncated:f}}}subgraph(t,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,a=new Set;for(let c of o)for(let d of this.#s.get(c)??[])i.has(d.source)&&i.has(d.target)&&this.#c(d,s)&&a.add(d);return{value:{nodes:o,edges:[...a].sort(ur)},meta:r.meta}}};function PT(e,t,n=qe){return{source:e,target:t.id,kind:n.require(t.kind).kind,createdAt:t.created_at,author:t.author}}import oh from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ca7f52c-fb31-5cd9-b689-a918f4e61816")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function Ae(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function eh(e){let t=e.key.trim();if(t.length===0)return null;let n=Ae(e.aliases),r=e.description?.trim();return{key:t,values:Ae(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var th=e=>e,qc=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function nh(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function rh(e,t){let n=new Map;for(let r of e??[]){let o=nh(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function Vc(e,t){return t?Ae(e):void 0}function ci(e){let t=e?.trim();return t&&t.length>0?t:void 0}function di(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function Wc(e,t={}){let n=t.resolvePolicyCommand??th,r=e.name.trim();if(r.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Ae(e.aliases),d=(e.options??[]).map(u=>eh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=rh(e.command_option_policies,n);return{name:r,description:ci(e.description),default_status:ci(e.default_status),...e.execution_role===void 0?{}:{execution_role:di(e.execution_role)},folder:ci(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Vc(e.required_create_fields,o),required_create_repeatables:Vc(e.required_create_repeatables,i),options:s?d:void 0,command_option_policies:a?l: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]="f40ddc8e-1dd5-5f26-b2ba-fbbac30a1781")}catch{}})();var ih=Object.freeze({decision:"human",milestone:"gate"}),sh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],ah=["dep","comment","note","learning","file","test","doc"],Kc=["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"],ch=["title","description","type","status","priority","tags","body",...Kc,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],dh=["title","description","body","status","closeReason","priority","type","tags",...Kc,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Yc={"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"},lh={...Yc},uh={...Yc},Xc=[["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"]],Jc=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Qc(e){return Object.fromEntries(e)}var fh=Qc([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Xc,["author","--author"],["message","--message"],["dep","--dep"],...Jc]),mh=Qc([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Xc,...Jc,["author","--author"],["message","--message"],["force","--force"]]);function ph(e){return e.trim().replace(/^--+/,"").toLowerCase()}function _h(e){return e==="create"?ch:dh}function hh(e){return e==="create"?lh:uh}function Zc(e,t){let n=ph(t);return n.length===0?void 0:hh(e)[n]||_h(e).find(r=>r.toLowerCase()===n)}function BT(e,t){return(e==="create"?fh:mh)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function ui(e){let t=yh(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function gh(e){let t=e.trim(),n=t.replaceAll("\\","/").replace(/^\/+/,""),r=oh.posix.normalize(n);if(t.includes("\0")||/^[A-Za-z]:/.test(r)||r==="."||r===".."||r.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return r}function yh(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 bh(e){return Wc(e,{resolvePolicyCommand:qc})}function sn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function wh(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 vh(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 Eh(e){if(Array.isArray(e.options))return e.options.map(t=>wh(t)).filter(t=>t!==null)}function Oh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>vh(t)).filter(t=>t!==null)}function Sh(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,execution_role:di(t.execution_role),folder:r,aliases:sn(t,"aliases"),required_create_fields:sn(t,"required_create_fields"),required_create_repeatables:sn(t,"required_create_repeatables"),options:Eh(t),command_option_policies:Oh(t)}}function kh(e,t){return e.required_create_fields?Ae(e.required_create_fields):t?.required_create_fields??[]}function Ah(e,t){return e.required_create_repeatables?Ae(e.required_create_repeatables):t?.required_create_repeatables??[]}function Ih(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Th(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Rh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=gh(e.folder??t?.folder??ui(n)),s={name:n,execution_role:e.execution_role,folder:i,aliases:Ae([...t?.aliases??[],...e.aliases??[]]),required_create_fields:kh(e,t),required_create_repeatables:Ah(e,t),options:Ih(e,t),command_option_policies:Th(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Gc(e,t){for(let n of e){let r=bh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Rh({...r,execution_role:r.execution_role??i?.execution_role},i))}}function Ch(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=Sh(o);i&&t.push(i)}}return t}function VT(e,t=null){let n=new Map;for(let c of jc)n.set(c.toLowerCase(),{name:c,execution_role:ih[c.toLowerCase()]??"agent",folder:tn[c],aliases:[],required_create_fields:[...sh],required_create_repeatables:[...ah],options:[],command_option_policies:[]});Gc(e.item_types?.definitions??[],n),Gc(Ch(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.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 d of c.aliases)i[d.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function xh(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Nh(e,t){let n=xh(e,t);if(n)return t.by_type[n]}function Dh(e,t,n,r){for(let o of r){let i=Zc(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function li(e,t,n){if(n){e.add(t);return}e.delete(t)}function Ph(e,t,n,r){let o=Zc(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&li(e.required,o,r.required),r.visible!==void 0&&li(e.hidden,o,!r.visible),r.enabled!==void 0&&li(e.disabled,o,!r.enabled)}function $h(e,t,n){for(let r of t.command_option_policies)r.command===n&&Ph(e,t,n,r)}function Mh(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function qT(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Dh(a,e,t,n),$h(a,e,t),Mh(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function jh(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function Lh(e,t,n){let r=e.values;if(r.length===0)return t;let o=new Map(r.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return o}function WT(e,t,n){let r=Nh(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=jh(r),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),u=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${l}" must not be empty`);continue}let f=i.get(l.toLowerCase());if(!f){let p=r.options.map(h=>h.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${p}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=Lh(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.name}"`);let a=Object.keys(s).sort((c,d)=>c.localeCompare(d));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as Fh,readdirSync as YT,realpathSync as ed,statSync as td}from"node:fs";import Uh from"node:os";import S 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]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();var zh={json_markdown:".md",toon:".toon"},Hh={".md":"json_markdown",".toon":"toon"};var nR=[".md",".toon"];function pr(e){try{return td(e),!0}catch{return!1}}function Bh(e){let t=S.resolve(e),n=[];for(;S.dirname(t)!==t;)try{return S.join(ed(t),...n)}catch(r){if(!me(r))throw r;n.unshift(S.basename(t)),t=S.dirname(t)}return S.join(ed(t),...n)}function Vh(e){try{return td(e),!0}catch(t){if(me(t))return!1;throw t}}function qh(e){try{let t=JSON.parse(Fh(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Wh(e){let t=Bh(e);for(;;){let n=S.join(t,or),r=S.join(n,ir);if(pr(r))return n;let o=S.join(t,ir);if(pr(o)&&qh(o))return t;if(Vh(S.join(t,".git")))return n;let i=S.dirname(t);if(i===t)return;t=i}}function fi(e){return Wh(e)??S.resolve(e,or)}function hr(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=S.resolve(e,r);if(!pr(_r(o))){let i=S.join(o,or);if(pr(_r(i)))return i}return o}return fi(e)}function nd(e){let t=S.resolve(e),n=S.dirname(t);return S.basename(t)==="pm"&&S.basename(n)===".agents"?S.dirname(n):t}function rd(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:S.join(Uh.homedir(),".pm-cli");return S.resolve(e,n)}function _r(e){return S.join(e,ir)}function Gh(e,t,n=tn){let r=n[t]??ui(t);return S.join(e,r)}function rR(e,t,n,r="toon",o=tn){return S.join(Gh(e,t,o),`${n}${zh[r]}`)}function oR(e){let t=e.replaceAll("\\","/"),n=S.posix.extname(t).toLowerCase();return Hh[n]??null}function iR(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new y("Invalid history item id: expected a single filename.",g.USAGE);return S.join(e,"history",`${t}.jsonl`)}function mi(e,t){return S.join(e,"locks",`${t}.lock`)}function od(e){return S.join(e,"runtime")}import Kh 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]="77f9d61e-e78b-5b6a-a769-1ad6e5b91777")}catch{}})();function Yh(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 Xh(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=gr(o))}return n}function gr(e){let t=Yh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>gr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return gr(r)}return Xh(e)}function A(e){return JSON.stringify(gr(e))}function id(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 Jh(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function Qh(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function Zh(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(!id(o,n,r,se))return!1;return!0}function eg(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(!id([o,i],n,r,([s,a],[c,d])=>se(s,c)&&se(a,d)))return!1;return!0}function tg(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>se(n,t[r]))}function ng(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!se(e[i],t[i]))return!1}return!0}var rg=[Jh,Qh,Zh,eg,tg];function se(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of rg){let r=n(e,t);if(r!==void 0)return r}return ng(e,t)}function At(e){return Kh.createHash("sha256").update(e,"utf8").digest("hex")}function We(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{createHash as ad}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]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();var og=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],sd=256,pi=64;function J(e){throw new y(`Invalid workflow policy: ${e}`,g.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function pe(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return J(`${n} must be an object`);let r=e;return Object.keys(r).some(o=>!t.includes(o))?J(`${n} contains an unknown key`):r}function Ge(e,t,n=128){return typeof e!="string"||!e.trim()||e.length>n?J(`${t} must be nonempty text of at most ${n} characters`):e.trim()}function an(e,t){if(!Array.isArray(e)||e.length===0||e.length>pi)return J(`${t} requires 1-${pi} terms`);let n=e.map(r=>Ge(r,t));return t==="fields"&&n.some(r=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(r)||r.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?J("fields must be safe metadata paths of at most eight segments"):[...new Set(n)]}function ig(e){let t=pe(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(pe(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>pi?J("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(n=>!Array.isArray(n)||n.length!==2?J("transition pairs need two statuses"):[Ge(n[0],"from"),Ge(n[1],"to")])}):t.kind==="authors"?(pe(t,["kind","authors"],"authors rule"),{kind:"authors",authors:an(t.authors,"authors")}):t.kind==="require_fields"?(pe(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:an(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(pe(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:an(t.fields,"fields"),authors:an(t.authors,"authors")}):J("unknown rule kind")}function sg(e){let t={},n=pe(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let r of["types","tags","statuses","operations","parents"])n[r]!==void 0&&(t[r]=an(n[r],r));if(n.dependency!==void 0){let r=pe(n.dependency,["kind","id"],"dependency");t.dependency={kind:Ge(r.kind,"dependency kind"),...r.id===void 0?{}:{id:Ge(r.id,"dependency id")}}}return t}function ag(e){let t=pe(e,["id","description","subject","effect","rule"],"policy"),n=Ge(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(n)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?J("effect must be advise, warn, or refuse"):{id:n,rule:ig(t.rule),...t.subject===void 0?{}:{subject:sg(t.subject)},...t.description===void 0?{}:{description:Ge(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:J("id must be a stable token")}function cg(e){let t=pe(e,["version","enforcement","policies"],"document");if(t.version!==1)return J("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return J("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>sd)return J(`policies must contain at most ${sd} declarations`);let n=t.policies.map(ag);return new Set(n.map(r=>r.id)).size!==n.length?J("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:n}}function yr(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function dg(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function cd(e){return ad("sha256").update(A(e)).digest("hex")}function lg(e,t){let n=e.rule.kind==="approval"?e.rule.fields:[];return ad("sha256").update(A({id:t.id,fields:n.map(r=>[r,yr(t,r)])})).digest("hex")}function ug(e,t){return Array.isArray(t)&&t.some(n=>typeof n=="object"&&n!==null&&"kind"in n&&n.kind===e.kind&&(e.id===void 0||"id"in n&&n.id===e.id))}function fg(e,t,n){return!(e.types&&!e.types.some(r=>r.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(n)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(r=>t.tags.includes(r)))||e.dependency&&!ug(e.dependency,t.dependencies))}function mg(e,t){if(t.completeness_only&&(e.rule.kind!=="require_fields"||e.subject?.operations!==void 0)||e.rule.kind==="approval"&&t.before===null)return!1;let n=e.subject??{},r=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&fg(n,{...o,status:r},t.operation))}function pg(e,t,n,r){let o=["type","tags","parent","dependencies"].some(i=>!se(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||n||r||o)?e.filter(i=>!dg(yr(t.after,i))):[]}function _g(e,t,n,r){let o=t.after??t.before,i=lg(e,o);return t.approvals?.some(s=>s.policy_fingerprint===r&&s.content_fingerprint===i&&s.author!==t.author&&n.includes(s.author))??!1}function hg(e,t,n){let r=e.rule,o=t.before?.status!==t.after?.status,i="fields"in r&&r.fields.some(s=>!se(yr(t.before,s),yr(t.after,s)));switch(r.kind){case"require_fields":{let s=pg(r.fields,t,o,i);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!o||r.allowed.some(([s,a])=>s===String(t.before?.status??"$create")&&a===String(t.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||_g(e,t,r.authors,n),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function dd(e,t,n){let r=e.policies.filter(o=>mg(o,t)).map(o=>{let i=o.effect??"advise",s=n(o);return{policy_id:o.id,policy_fingerprint:s,rule:o.rule.kind,effect:i==="refuse"&&e.enforcement!=="refuse"?"warn":i,...hg(o,t,s)}});return{allowed:!r.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:r,warnings:r.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function mR(e,t){return dd(e,t,cd)}function pR(e){let t=cg(e),n=new Map(t.policies.map(r=>[r,cd(r)]));return r=>dd(t,r,o=>n.get(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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var gg=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-tqel"})),yg=[...["next","focus"].map(e=>({alias:e,canonical:`context ${e}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-6apl"})),...["normalize","reindex"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(e=>({...e,canonical_argv:e.canonical.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap"})),bg=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-ik19"})),wg=[...yg,...bg,...["init","config","schema","profile"].map(e=>({alias:e,canonical:`workspace ${e}`,canonical_argv:["workspace",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(e=>[e,`item ${e}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(e=>[`completion-${e}`,`completion ${e}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(e=>[e,`calendar ${e}`,"pm-o3fh"])].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:n}))],_i=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...gg,...wg,...["discover","lookup"].map(e=>({alias:`files ${e}`,canonical:`item files ${e}`,canonical_argv:["item","files",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-yql1"}))];function hR(e){let t;for(let n of _i)n.canonical_argv.length<=(t?.canonical_argv.length??0)||n.canonical_argv.every((r,o)=>r===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=n);return t}function vg(e){let t=e.trim().replace(/\s+/gu," ");return _i.find(n=>n.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function cn(e){return vg(e)}var br=[..._i,...[["ctx","context"],["packages","package"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:[t,n],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:["comments","notes","learnings"].includes(t)?`item ${t}`:t,canonical_argv:["comments","notes","learnings"].includes(t)?["item",t]:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],gR=Object.fromEntries(br.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function yR(e){let t=e.trim().toLowerCase();return br.find(n=>n.alias===t)}function bR(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3348c61d-a03e-5023-a5dc-fd6149f478c1")}catch{}})();var Eg=[...fe],Og=[...St],Sg=[...er],SR=[...tr],kR=[...nr],kg=[...rr],wr=["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-attest","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"],AR=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],IR=["install","reconcile","report","driver"],Ag=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Ig=["upgrade"],Tg=["reopen"],ld={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},It=Object.freeze(wr.flatMap(e=>e in ld?[]:e==="extension"||e==="package"?[...Ag.map(t=>`${e}-${t}`),...e==="package"?Ig.map(t=>`package-${t}`):[],e]:e==="item"?Tg.map(t=>`item-${t}`):[e])),Rg=Object.freeze(br.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&It.includes(e.alias)).map(e=>e.alias)),TR=Object.freeze(It.filter(e=>!Rg.includes(e)));function RR(e=wr,t=It,n=ld){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function CR(e){return It.includes(e)}function xR(e){return Eg.includes(e)}function NR(e){return Og.includes(e)}function DR(e){return Sg.includes(e)}function PR(e){return kg.includes(e)}var $R=new Set(["update","item-reopen","close","claim","release","start-task","pause-task","close-task","restore","append","update-many","close-many","delete","comments","notes","learnings","files","docs","test","test-all","plan","history-redact","history-repair","history-compact","validate"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="447bb510-051a-5dce-8b7d-e27f4ca781f4")}catch{}})();var vr={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},Er=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Ke=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","learnings","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8657910-1392-5fae-afda-614b96dc8320")}catch{}})();function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Cg(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function ud(e){return e?W(e):{}}function fd(e){return e?W(e):Cg()}function W(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]="615b4955-a30d-5d45-a86d-4bcf7bd9bd7a")}catch{}})();var xg=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),Ng=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function Dg(e,t){for(let n of Ng){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>xg.has(n)?N(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function Pg(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>N(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function $g(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>N(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function Or(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let n={schema_version:1};if(!Dg(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=Pg(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=$g(i);if(s===null)return null;n.preflight_ownership=s}return n}function UR(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4155698-c244-5623-b627-92dd25297125")}catch{}})();var Mg=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields",extension_command_availability:"read_output"},{flag:"--output-limit",value_name:"count",extension_command_availability:"read_output"},{flag:"--output-budget",value_name:"tokens",extension_command_availability:"read_output"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state",extension_command_availability:"read_output"},{flag:"--output-cursor",value_name:"cursor",extension_command_availability:"read_output"},{flag:"--output-row-contract",extension_command_availability:"read_output"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"],discovery_value_name:"path"},{flag:"--no-extensions",extension_command_availability:"never"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),Sr=new Set(Mg.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]="81054684-60df-57c9-af9d-0996874c1024")}catch{}})();var md=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function hi(e){if(typeof e!="string")return null;let t=md.exec(e.trim());if(!t)return null;let n=t[2];return{name:t[1],valueName:n?n.slice(1,-1):null,optional:n?.startsWith("[")??!1}}function VR(e){let t=hi(e);return t?t.name:typeof e=="string"&&e.trim()||null}function jg(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return Sr.has(n)||Sr.has(`--${n.slice(2).replaceAll("_","-")}`)?"host_owned_flag_collision":md.test(t)?null:"malformed_long_flag"}function pd(e,t){let n=[e,t].find(i=>typeof i=="string"&&Sr.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=jg(r);return o===null?null:{token:r,failure:o}}function _d(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c3049c3-1d5a-5e7e-a070-35340737a6ab")}catch{}})();var hd=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function kr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(hd,t)?hd[t]:null}function Lg(e,t,n){return!!(e.value_name?.trim()||t||n||e.required===!0||e.list===!0||e.repeatable===!0)}function Fg(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function GR(e){let t=Fg(e),n=kr(t),r=hi(e.long),o=e.value_name?.trim()||null,i=!(n==="boolean"&&t!=="bool")&&Lg(e,r?.valueName,t),s=r?.valueName?r.optional:t==="bool";return{value_type:n,value_arity:i?s?"optional":"required":"none",value_name:i?o??r?.valueName??"value":null}}function gd(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function yd(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}function KR(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e)?null:{kind:t,received:e,expected:"a finite number"}:typeof e=="boolean"?null:{kind:t,received:e,expected:"true, false, 1, or 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]="f74cf2ed-6219-57c6-98a3-4b4c7496a17c")}catch{}})();function Ug(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ie(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1),o=e.charCodeAt(n.length);return r>=55296&&r<=56319&&o>=56320&&o<=57343?n.slice(0,-1):n}var dn=240,bd=/\u2026\[\+([1-9]\d*) chars\]$/u;function Ar(e){if(e.length<=dn)return e;let t=bd.exec(e);if(t!==null&&t.index<=dn)return e;let n=Ie(e,dn);return`${n}\u2026[+${e.length-n.length} chars]`}function XR(e){let t=bd.exec(e.trimEnd());return t?Number(t[1]):void 0}function ln(e){return e==="cursor"||e.endsWith("_cursor")}var zg=new Set(["get","list","search"]);function Ir(e,t){return(t==="item"||t==="items")&&e!==void 0&&zg.has(e)}function Tr(e){return e.includes("\u2026")}function JR(e){return Ug(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function QR(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).size;return o/i}import vd from"node:path";import{link as Hg,mkdir as Bg,mkdtemp as Vg,open as qg,rm as Wg,writeFile as Gg}from"node:fs/promises";import gi 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]="1c52c822-3fe3-5afd-8ac1-182e7a18dbde")}catch{}})();var Kg=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]),yi=class extends Error{code;constructor(t,n){super(`The filesystem cannot publish a file by hard link (${t}).`,{cause:n}),this.name="AtomicLinkUnsupportedError",this.code=t}};async function Yg(e,t){let n=await qg(e,"wx");try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}}async function wd(e,t,n={}){let r=gi.dirname(e);await Bg(r,{recursive:!0});let o=await Vg(gi.join(r,".pm-seed-")),i=gi.join(o,"value");try{await(n.sync===!0?Yg(i,t):Gg(i,t,"utf8"));try{return await Hg(i,e),!0}catch(s){let a=s.code??"";if(a==="EEXIST")return!1;throw Kg.has(a)?new yi(a,s):s}}finally{await Wg(o,{recursive:!0,force:!0}).catch(()=>{})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function Rr(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=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]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var Xg=2e3,Cr=new Map;function Te(e){if(typeof e!="string")return"";let t=Cr.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Cr.size>=Xg&&Rr(Cr),Cr.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]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ae=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Sd=Dc,wi=Nc,Jg=["create","update"],Qg=new Set(Lc),Zg=new Set(ar),ey=new Set(Fc),ty=new Set(Uc),ny=new Set(["string","number","boolean","array","object"]),ry=16;function kd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var oy=[e=>e.type===void 0||typeof e.type=="string"&&ny.has(e.type),e=>!Object.hasOwn(e,"const")||Nr(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Nr(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||kd(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Nr(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=>Nr(r,t)):Object.values(e).every(r=>Nr(r,t));return t.delete(e),n}function xr(e,t=0,n=new Set){if(!kd(e)||t>ry||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,d=r.required,l=r.min_length,u=r.min_items,f=r.format,m=r.additional_properties;if(!oy.every(b=>b(r))){n.delete(e);return}let p=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([b,E])=>[b,xr(E,t+1,n)])),h=c===void 0?void 0:xr(c,t+1,n),_=s===void 0?void 0:s.map(b=>xr(b,t+1,n));if([...Object.values(p??{}),...c===void 0?[]:[h],..._??[]].some(b=>b===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:l,min_items:u,format:f,properties:p,required:d===void 0?void 0:[...new Set(d)],additional_properties:m,items:h,one_of:_}).filter(([,b])=>b!==void 0))}function fn(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 Z(e){if(typeof e!="string"||e.length===0)return;let t=Te(e);return t.length>0?t:void 0}function iy(e){return e.startsWith("--")?e.slice(2):e}function Ed(e){return typeof e=="string"?iy(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Ad(e){return e.replaceAll("_","-")}function sy(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function bi(e,t){let n=Z(e.id);if(!n)return null;let r=[...new Set(fn(e.aliases).map(Te).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=fn(e.roles).filter(a=>Qg.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 ay(e){return{draft_status:Z(e?.draft_status),open_status:Z(e?.open_status),in_progress_status:Z(e?.in_progress_status),blocked_status:Z(e?.blocked_status),close_status:Z(e?.close_status),canceled_status:Z(e?.canceled_status)}}function Id(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Te(t[0]),r=Te(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function cy(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)Id(n,r);return{typeKey:t.toLowerCase(),record:n}}function dy(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=cy(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)Id(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 Td(e){let t=Te(e.key??"");if(!t)return null;let n=Te(e.metadata_key??e.front_matter_key??t),r=Ed(e.cli_flag??Ad(t));if(!r)return null;let o=fn(e.cli_aliases).map(u=>Ed(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=Zg.has(i)?i:"string",a=(()=>{let u=fn(e.commands).filter(f=>ey.has(f));return u.length>0?u:[...Jg]})(),c=e.description?.trim(),d=fn(e.required_types),l=e.value_schema===void 0?void 0:xr(e.value_schema);return e.value_schema!==void 0&&l===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:d,allow_unset:e.allow_unset!==!1,value_schema:l}}function ly(e){let t=new Map;for(let[r,o]of e.entries()){let i=bi(o,r);i&&t.set(i.id,i)}let n=Od([...t.values()]);return n.length>0?n:Od(wi.map((r,o)=>bi(r,o)).filter(r=>r!==null))}function Od(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function uy(e){let t=new Map;for(let n of e??[]){let r=Td(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function fy(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 my(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Ad(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 py(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return ty.has(t)?t:"allow"}function mn(e){let t={...ae,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:wi,r=ly(n),o=uy(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(fy),fields:o.map(my),workflow:{...Sd,...ay(e?.workflow)},type_workflows:dy(e?.type_workflows),unknown_field_policy:py(e?.unknown_field_policy)}}function _y(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function hy(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 gy(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 yy(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 by(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 wy(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 _e(e,t,n){let r=t?.trim()||n;return vd.isAbsolute(r)?r:vd.join(e,r)}function fC(e,t){return _e(e,t.files.types,ae.types)}async function mC(e,t){let n=mn(t),r=[{path:_e(e,n.files.types,ae.types),seed:{definitions:[]}},{path:_e(e,n.files.statuses,ae.statuses),seed:{statuses:wi}},{path:_e(e,n.files.fields,ae.fields),seed:{fields:[]}},{path:_e(e,n.files.workflows,ae.workflows),seed:{workflow:Sd}}],o=[];for(let i of r)await nn(i.path)||await wd(i.path,`${JSON.stringify(i.seed,null,2)}
|
|
2
|
+
`)&&o.push(i.path);return{created_paths:o}}async function pC(e,t){let n=mn(t),r=[],o=_e(e,n.files.types,ae.types),i=_e(e,n.files.statuses,ae.statuses),s=_e(e,n.files.fields,ae.fields),a=_e(e,n.files.workflows,ae.workflows),c,d,l,u,f,m=async(E,j)=>{let X=await Pc(E);if(X!==null)return _y(X,j,r)},p=await m(o,"runtime_schema_types_invalid_json");p!==void 0&&(c=hy(p),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let h=await m(i,"runtime_schema_statuses_invalid_json");h!==void 0&&(d=gy(h),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let _=await m(s,"runtime_schema_fields_invalid_json");_!==void 0&&(l=yy(_),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let b=await m(a,"runtime_schema_workflows_invalid_json");return b!==void 0&&(u=by(b),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=wy(b)),{schema:mn({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function un(e,t,n,r=!1){let o=n.map(s=>Z(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(r&&o!==void 0)return o;let i=e.find(s=>s.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function vy(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function Ey(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Rd(e){let t=mn(e),n=t.statuses.map((b,E)=>bi(b,E)).filter(b=>b!==null),{aliasToId:r,byId:o}=vy(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=Ey(n),u=t.workflow,f=Z(u.open_status)??un(n,"default_open",["open","in_progress",kt[0]]),m=Z(u.in_progress_status)??un(n,"active",["in_progress","in-progress",f],!0),p=Z(u.blocked_status)??un(n,"blocked",["blocked"]),h=Z(u.close_status)??un(n,"default_close",["closed","done","complete"]),_=Z(u.canceled_status)??un(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:l,terminal_done_statuses:d,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:m,blocked_status:p,close_status:h,canceled_status:_}}function vi(e,t){let n=Te(e);if(n)return t.alias_to_id.get(n)}function Cd(e){let t=mn(e),n=new Map,r=t.fields.map(c=>Td(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,d)=>c.key.localeCompare(d.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 d of c.cli_aliases)s.set(d,c);for(let d of c.commands){let l=a.get(d)??[];l.push(c),a.set(d,l)}}for(let[c,d]of a.entries())d.sort((l,u)=>l.key.localeCompare(u.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function xd(e){return sy(e.key)}function _C(e,t){let n=vi(e,t);return n?t.terminal_statuses.has(n):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();var Nd=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],Dd=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default","transaction_abandon"],Ei={"init:type-preset":"init:type_preset"},Pd=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],gC={version:1,item:Nd,workspace:Dd,aliases:Ei,patterns:Pd,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},Oy=new Set([...Nd,...Dd]),Sy=Pd.map(e=>new RegExp(e,"u"));function $d(e){return Object.hasOwn(Ei,e)?Ei[e]:e}function yC(e){let t=$d(e);if(Oy.has(t)||Sy.some(n=>n.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function Md(e){let t=$d(e),n=t.indexOf(":"),r=n<0?t:t.slice(0,n),o=n<0||n<t.length-1&&!/[\s\p{C}]/u.test(t.slice(n+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(r)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{createHash as ky}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]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var vC=["sha256","sha512"],Ay="sha256",jd="sha256";function re(e){if(e===void 0)return Ay;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function ce(e,t){return ky(re(t)).update(e,"utf8").digest("hex")}import Iy from"node:crypto";import{AsyncLocalStorage as Ty}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]="ced47074-06d3-53b9-af75-63586cbd4f6a")}catch{}})();var Fd=new Ty,Ld=1024;function Ud(){let e=Fd.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 kC(e){let t=Fd.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Ld)throw new Error(`Reproducible token length must be an integer between 0 and ${Ld}`);let n="";for(;n.length<e;){let r=Iy.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}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]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var Ry=/^([+-]?)(\d+)([hdwm])$/i,Cy=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,xy=/^(\d{4})(\d{2})(\d{2})$/,Ny=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Dy=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Py=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,$y=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function pn(){return Ud()??new Date().toISOString()}function he(e){return Number.isFinite(Date.parse(e))}function _n(e){let t=$y.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,d]=t,[l,u,f,m,p,h]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=ki(l,u-1)&&m<=23&&p<=59&&h<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function Tt(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return _n(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var My=1e4,Dr=new Map;function zd(e){let t=Dr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Dr.size>=My&&Rr(Dr),Dr.set(e,n),n}function G(e,t){let n=zd(e),r=zd(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function xC(e,t){return!(t.deadlineBefore&&(!e.deadline||G(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||G(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&G(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&G(e.updated_at,t.updatedBefore)>0||t.createdAfter&&G(e.created_at,t.createdAfter)<0||t.createdBefore&&G(e.created_at,t.createdBefore)>0)}function Oi(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function Si(e){if(!e)return"";if(e.toUpperCase()==="Z")return"Z";let t=/^([+-]\d{2})(\d{2})$/.exec(e);return t?`${t[1]}:${t[2]}`:e}function jy(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function Ly(e){let t=[],n=d=>jy(t,e,d),r=xy.exec(e);if(r){let[,d,l,u]=r;n(`${d}-${l}-${u}`)}let o=Ny.exec(e);if(o){let[,d,l,u,f,m,p,h,_]=o,b=p?`:${p}`:"";n(`${d}-${l}-${u}T${f}:${m}${b}${Oi(h)}${Si(_)}`)}let i=Dy.exec(e);if(i){let[,d,l,u,f,m,p]=i,h=f?`:${f}`:"";n(`${d}T${l}:${u}${h}${Oi(m)}${Si(p)}`)}let s=Py.exec(e);if(s){let[,d,l,u,f,m,p]=s,h=f?`:${f}`:"";n(`${d}T${l}:${u}${h}${Oi(m)}${Si(p)}`)}let a=10,c=e.slice(0,a);if(Uy(c)){let d=a;for(;d<e.length&&zy(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Fy(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of Ly(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Uy(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function zy(e){return e?e===" "||e===" "||e===`
|
|
3
|
+
`||e==="\r"||e==="\f"||e==="\v":!1}function ki(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Hy=["January","February","March","April","May","June","July","August","September","October","November","December"],By=/^(\d{4})-(\d{2})-(\d{2})/,Vy=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function qy(e,t,n){let r=By.exec(t)??Vy.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new y(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,g.USAGE,{field:a,value:e});let c=ki(o,i-1);if(s<1||s>c)throw new y(`Invalid ${a} value "${e}". ${Hy[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,g.USAGE,{field:a,value:e})}function Wy(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,ki(i,s));return n.setUTCFullYear(i,s,a),n}function NC(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=Ry.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return Wy(t,a).toISOString();let d=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*d).toISOString()}qy(e,r,n);let i=Fy(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Cy.test(r)?"Compound relative expressions like +3d+1h are not supported; use a single relative token (for example +3d) or an ISO/date string.":'Use ISO/date string input, "now", or relative +6h/-6h/+1d/-1d/+2w/-2w/+6m/-6m.';throw new y(`Invalid ${s} value "${e}". ${a}`,g.USAGE,{field:s,value:e})}return new Date(i).toISOString()}import{AsyncLocalStorage as Gy}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]="86412887-5659-5892-beaa-bdd15a02ff4c")}catch{}})();var Ai=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},Hd=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?Ai(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,oe=(e,t=process.platform)=>{let n=e.map(r=>Hd(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6bebd48-2722-5784-b69b-cf18321ea2c0")}catch{}})();var Ti="[redacted]";function Ky(e,t){if(/[\t\n\r]/u.test(e)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(e.slice(0,t)))return!1;let n=t+1;for(;e[n]==="/"||e[n]==="\\";)n+=1;let r=e.indexOf("/",n)-n;if(r<0)return!1;let o=n+r;return!/[:@%]/u.test(e.slice(n,o))&&!/[:%]|[/\\][/\\]/u.test(e.slice(o))}function Bd(e){let t=Math.max(e.lastIndexOf("@"),e.toLowerCase().lastIndexOf("%40")),n=e.indexOf(":");if(t<0||n<0||n>t)return;let r=n+1;for(;r<t&&r<n+3&&(e[r]==="/"||e[r]==="\\");)r+=1;return r===t||Ky(e,n)?void 0:[r,t]}function Ri(e){let t=Bd(e);return t?`${e.slice(0,t[0])}${Ti}${e.slice(t[1])}`:e}function Vd(e){return Ri(e)}var qd=["author","assignee","claim_principal"];function FC(e){let t={...e};for(let n of qd)typeof t[n]=="string"&&(t[n]=Vd(t[n]));return t}function Rt(e,t){if(!(typeof e!="string"||Bd(e.trim())===void 0))throw new y(`${t} must not carry URL credentials: an identity is a name, never a credential.`,g.USAGE,{code:"invalid_argument_value",field:t,required:`Set ${t} to a plain name such as agent-a, with no URL userinfo (no user, password or token before the host).`,nextSteps:[`Rerun with ${t} set to a plain name.`],url_credentials_rejected:{source:t}})}function UC(e,t){return Rt(e,t),e}var Yy=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],Xy=4;function Ii(e,t,n=0){if(typeof e=="string"){Rt(e,t);return}if(!(n>=Xy||typeof e!="object"||e===null))for(let r of Object.values(e))Ii(r,t,n+1)}function Jy(e,t){let n=e;for(let r of t){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function Wd(e){let t=e;for(let n of qd)Ii(t[n],n);for(let[n,...r]of Yy){let o=t[n];Array.isArray(o)&&o.forEach((i,s)=>{Ii(Jy(i,r),`${n}[${s}].${r.join(".")}`)})}}function zC(e){return typeof e=="string"?Vd(e):e}var Qy=6;var Zy={carried:!1,fragments:new Set,fragmentLength:Qy,shortSpellings:[]},eb=new Gy;function tb(e){let t=e.toLowerCase();if(t.length===e.length)return t;let n="";for(let r of e){let o=r.toLowerCase();n+=o.length===r.length?o:r}return n}function nb(e,t){let n=tb(e),r=new Uint8Array(e.length),o=!1,i=t.fragmentLength;for(let a=0;a+i<=n.length;a+=1)t.fragments.has(n.slice(a,a+i))&&(r.fill(1,a,a+i),o=!0);for(let a of t.shortSpellings)for(let c=n.indexOf(a);c>=0;c=n.indexOf(a,c+1))r.fill(1,c,c+a.length),o=!0;if(!o)return e;let s="";for(let a=0;a<e.length;a+=1)r[a]?(a===0||!r[a-1])&&(s+=Ti):s+=e[a];return s}function rb(e){let t=eb.getStore()??Zy,n=t.carried?nb(e,t):e;return/@|%40/iu.test(n)?n.replaceAll(/\S+/gu,Ri):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]="9b51a9f9-e57f-5998-837e-c6c442ca1c9b")}catch{}})();var ob=16;function Pr(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function YC(e,t,n=new Set,r){if(Xd(e,t,r))return;let o=Jd(e,t,n,r),i=$r(e);return[Pr(e.cli_flag),...i].find(s=>!o.has(s)&&Yd(s,i,o))}function Yd(e,t,n){for(let r of t){if(r===e)break;if(n.has(r))return!1}return!0}function Xd(e,t,n){return t.definitions.some(r=>r!==e&&r.metadata_key===e.metadata_key&&(n===void 0||r.commands.includes(n)))}function Jd(e,t,n,r){return new Set([...n,...t.definitions.filter(o=>o!==e&&(r===void 0||o.commands.includes(r))).flatMap(o=>$r(o))])}function Qd(e){return e.replace(/^-+/u,"").startsWith("no-")}function ib(e){return e.startsWith("-")?e:`--${e}`}function XC(e,t,n,r){if(Xd(e,t,r))return;let o=Jd(e,t,n.options,r),i=$r(e);return[e.cli_flag,...e.cli_aliases].find(s=>{let a=Zd(s);return Qd(s)||n.flags.has(ib(s))||o.has(a)?!1:Yd(a,i,o)})}function Zd(e){return e.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((t,n)=>`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`)}function $r(e){return[...new Set([xd(e),Pr(e.key),Pr(e.cli_flag),...e.cli_aliases.map(t=>Pr(t)),...[e.cli_flag,...e.cli_aliases].filter(t=>!Qd(t)).map(t=>Zd(t))])]}function el(e,t){for(let n of $r(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function tl(e){return Array.isArray(e)?e.flatMap(t=>tl(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 Gd(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 Kd(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 sb(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 ab(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 cb(e,t,n){if(t.const!==void 0&&A(e)!==A(t.const))return`${n} must equal ${A(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>A(r)===A(e)))return`${n} must be one of ${t.enum.map(r=>A(r)).join("|")}`;if(!ab(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"&&!_n(e))return`${n} must be an RFC 3339 date-time`}}function db(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 lb(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>ob)return`${n} value schema exceeds maximum depth`;let o=cb(e,t,n);if(o)return o;let i=db(e,t,n,r);if(i)return i;let s=lb(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 Ye(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,g.USAGE);return t}function ub(e,t,n,r){let o=r==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Ye(e,sb(o,n,e.type),n)}function hn(e,t,n,r="option"){let o=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return ub(e,t,o,r);if(e.repeatable||e.type==="string_array"){let s=tl(t);return e.type==="number"?Ye(e,s.map(a=>Kd(a,o)),o):e.type==="boolean"?Ye(e,s.map(a=>Gd(a,o)),o):Ye(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Ye(e,Kd(i,o),o):e.type==="boolean"?Ye(e,Gd(i,o),o):Ye(e,typeof i=="string"?i:String(i),o)}function fb(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function JC(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=el(e,i);if(s===void 0){fb(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=hn(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function QC(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=el(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=hn(s,a)))}return Wd(r),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]="ec8ac553-25db-5fb1-bf2f-555815d7b283")}catch{}})();var Ci=1,xi=4;function ex(e){let t=e.tests??[],n=t.some(o=>o.phase==="setup")?3:t.some(o=>o.updated_by!==void 0||o.updated_at!==void 0)?2:1,r=(e.deferred_fields?.length??0)>0?4:1;return Math.max(Ni(e),n,r)}function Ni(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function nl(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function mb(e,t=4,n=t){return e<n?"outdated":e>t?"ahead":"current"}function tx(e,t=4,n=t){let r=[],o=[];for(let i of e){let s=mb(i.version,t,n);s==="outdated"?r.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:r.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(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]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var pb={"in-progress":"in_progress",cancelled:"canceled"};function jr(e,t){if(t){let o=vi(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=pb[n]??n;if(kt.includes(r))return r}function _b(e,t){return jr(e,t)??e}function ix(e,t){return t.terminal_statuses.has(_b(e,t))}import{encode as Ob}from"@toon-format/toon";import{isDeepStrictEqual as dl}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]="b24a4ce2-c356-56ee-8a34-f48a78507ac4")}catch{}})();var Di=[{field:"acceptance_criteria",option:"acceptanceCriteria",flag:"--acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","acceptancecriteria","ac"]},{field:"assignee",option:"assignee",flag:"--assignee",aliases:["assignee"]},{field:"deadline",option:"deadline",flag:"--deadline",aliases:["deadline"]},{field:"estimated_minutes",option:"estimatedMinutes",flag:"--estimate",aliases:["estimated_minutes","estimated-minutes","estimatedminutes","estimate"]}],rl=new Map(Di.map(e=>[e.field,e])),hb=new Map(Di.flatMap(e=>e.aliases.map(t=>[t,e])));function ax(e){return hb.get(e.trim().toLowerCase())}function cx(e){return rl.get(e)}function gb(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0:typeof n=="number"?Number.isFinite(n):n!=null}function yb(e){return(e.deferred_fields??[]).filter(t=>!gb(e,t.field))}function dx(e){let t=e.deferred_fields;if(t===void 0||t.length===0)return!1;let n=yb(e);return n.length===t.length?!1:(n.length===0?delete e.deferred_fields:e.deferred_fields=n,!0)}function ol(e){if(e===void 0)return;if(!Array.isArray(e))return"deferred_fields must be an array";let t=new Set;for(let[n,r]of e.entries()){if(typeof r!="object"||r===null||Array.isArray(r))return`deferred_fields[${n}] must be an object`;let{field:o,reason:i}=r;if(typeof o!="string"||!rl.has(o))return`deferred_fields[${n}].field must be one of ${Di.map(s=>s.field).join(", ")}`;if(typeof i!="string"||i.trim().length===0)return`deferred_fields[${n}].reason must be a non-empty string`;if(t.has(o))return`deferred_fields lists ${o} more than once`;t.add(o)}}function il(e){if(!(e===void 0||e.length===0))return e.map(t=>({field:t.field,reason:t.reason.trim()})).sort((t,n)=>t.field.localeCompare(n.field))}import{decode as bb}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]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function Pi(e){return{value:bb(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]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var wb=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function vb(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(wb);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Lr(e){return vb(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function Eb(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function px(e){return Eb(e)??void 0}function _x(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function hx(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function al(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Fr(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 gx(e){let t=Fr(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function yx(e,t,n){let r=Fr(e);return r===null||r<t||r>n?null:r}function bx(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function Re(e){return typeof e!="object"||e===null?null:e}function sl(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function cl(e){let t=sl(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=sl(t.default);return typeof n?.activate=="function"?n:null}function wx(e){return typeof e=="object"&&e!==null&&!Array.isArray(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]="5eaa8bf7-ef0a-51a2-a206-274e9d4c5f82")}catch{}})();var Li=new Set(["schema","tracker","auto","none"]),pl=new Set(["source","isolated","snapshot"]),Sb=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),kb=new Set(["passed","failed","stopped","canceled"]),Ab=new Set(zc);function Dt(e){return e.replaceAll("\\","/")}function _l(e){for(let t of e)if(t!==0)return t;return 0}function zr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var hl=["id","title","description","created_at","updated_at"],Ib=new Set(ke);function gl(e){if(e?.schema)return{statusRegistry:Rd(e.schema),fieldRegistry:Cd(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Tb(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Ce(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 bn(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 yl(e,t){if(!t||typeof e!="object"||e===null)return;let n=Ni(e);if(!(n<=xi))throw new y(`Stored item uses format version ${n}; this runtime supports up to ${xi}. Upgrade pm before reading or changing this item.`,g.CONFLICT,{code:"item_format_version_unsupported",format_version:n,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function bl(e){let t=new Set(Ib);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function v(e,t){e||Ce(t)}function wn(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Ce(t),e}function $i(e,t){let n=e[t];v(typeof n=="string",`${t} must be a string`),v(he(n),`${t} must be a valid ISO timestamp`)}function ll(e,t,n){let r=e[t];r!==void 0&&v(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Fi(e,t,n){let r=e[t];r!==void 0&&(v(typeof r=="string",`${n} must be a string`),v(he(r),`${n} must be a valid ISO timestamp`))}function Rb(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){v(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();v(rn.includes(n),`event.recurrence.by_weekday entries must be one of: ${rn.join(", ")}`)}}}function Cb(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)v(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function xb(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)v(typeof t=="string","event.recurrence.exdates entries must be strings"),v(he(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Nb(e){let t=wn(e,"event.recurrence must be an object");v(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();v(lr.includes(n),`event.recurrence.freq must be one of: ${lr.join(", ")}`),ll(t,"interval","event.recurrence.interval"),ll(t,"count","event.recurrence.count"),Fi(t,"until","event.recurrence.until"),Rb(t.by_weekday),Cb(t.by_month_day),xb(t.exdates)}function Db(e){for(let r of hl)v(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;v(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&v(typeof n=="number"&&Number.isInteger(n)&&n>=Ci,`pm_format_version must be an integer >= ${Ci}`),t}function Pb(e,t){let n=e.status;v(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=jr(n,r),i=r?r.definitions.map(s=>s.id):[...kt];v(o!==void 0,`status must be one of: ${i.join(", ")}`)}function $b(e){let t=e.priority;v(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;v(Array.isArray(n),"tags must be an array");for(let r of n)v(typeof r=="string","tags entries must be strings")}function Mb(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){v(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"||dr.includes(n);v(r,`confidence string value must be one of: ${[...dr,"med"].join(", ")}`);return}v(!1,"confidence must be a number or string")}}function jb(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Ce("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||cr.includes(n);v(r,`severity value must be one of: ${[...cr,"med"].join(", ")}`)}function Lb(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Ce("regression must be a boolean")}function Fb(e){let t=e.reminders;if(t!==void 0){v(Array.isArray(t),"reminders must be an array");for(let n of t){let r=wn(n,"reminders entries must be objects");v(typeof r.at=="string","reminder.at must be a string"),v(he(r.at),"reminder.at must be a valid ISO timestamp"),v(typeof r.text=="string","reminder.text must be a string"),v(r.text.trim().length>0,"reminder.text must not be empty")}}}function Ub(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(v(typeof e[t]=="string",`event.${t} must be a string`),v(e[t].trim().length>0,`event.${t} must not be empty`))}function zb(e){e.recurrence!==void 0&&(Nb(e.recurrence),e.recurrence.until!==void 0&&v(G(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Hb(e){let t=wn(e,"events entries must be objects");v(typeof t.start_at=="string","event.start_at must be a string"),v(he(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(v(typeof t.end_at=="string","event.end_at must be a string"),v(he(t.end_at),"event.end_at must be a valid ISO timestamp"),v(G(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Ub(t),t.all_day!==void 0&&v(typeof t.all_day=="boolean","event.all_day must be a boolean"),zb(t)}function Bb(e){let t=e.events;if(t!==void 0){v(Array.isArray(t),"events must be an array");for(let n of t)Hb(n)}}function Vb(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&v(typeof n=="string",`${t} must be a string`)}}function qb(e){let t=e.type_options;if(t===void 0)return;let n=wn(t,"type_options must be an object");for(let[r,o]of Object.entries(n))v(r.trim().length>0,"type_options keys must be non-empty"),v(typeof o=="string","type_options values must be strings"),v(o.trim().length>0,"type_options values must be non-empty strings")}function Wb(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Tb(r,t)&&Ce(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=hn(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){Ce(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Gb(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=bl(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Ce(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ui(e,t){let n=wn(e,"item metadata must be an object"),r=Db(n);Pb(n,t),$b(n),Mb(n),jb(n),Lb(n),$i(n,"created_at"),$i(n,"updated_at"),n.deadline!==void 0&&$i(n,"deadline"),Fb(n),Bb(n),Fi(n,"closed_at","closed_at"),Fi(n,"completed_at","completed_at"),Vb(n),qb(n);let o=ol(n.deferred_fields);v(o===void 0,o??""),Wb(n,r,t),Gb(n,t)}function Kb(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(v(t.created_at===void 0||typeof t.created_at=="string"&&_n(t.created_at),`dependencies.${n}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=G(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??"")})}var jx=new Set(["comments","notes","learnings"]),Yb="[unconvertible]";function Ct(e,t){try{return String(e?.[t])}catch{return Yb}}function Xb(e,t){let n=G(Ct(e,"created_at"),Ct(t,"created_at"));if(n!==0)return n;let r=Ct(e,"text").localeCompare(Ct(t,"text"));return r!==0?r:Ct(e,"author").localeCompare(Ct(t,"author"))}function Mi(e){if(!(!e||e.length===0))return[...e].sort(Xb)}function Jb(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=G(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function Qb(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!lr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>rn.includes(s)))).sort((s,a)=>ni(s)-ni(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=>he(s)))).sort((s,a)=>G(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 Zb(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(ew).sort(tw)}function ew(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:Qb(e.recurrence)};return zr(t),t}function tw(e,t){return _l([G(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 nw(e){if(!(!e||e.length===0))return e.map(t=>({path:Dt(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function rw(e){if(!e||e.length===0)return;let t=e.map(aw).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)=>_l([G(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 xt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function ow(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function ji(e){return typeof e=="string"?e:""}function iw(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 Ur(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function sw(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:Ur(n.requested_pm_context_mode,Li),pm_context_mode:Ur(n.pm_context_mode,Li),workspace_context_mode:Ur(n.workspace_context_mode,pl),trust_reason:Ur(n.trust_reason,Sb)}));return t.length>0?t:void 0}function aw(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=kb.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:ji(e.started_at),finished_at:ji(e.finished_at),recorded_at:ji(e.recorded_at),attempt:ow(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:xt(e.passed)??0,failed:xt(e.failed)??0,skipped:xt(e.skipped)??0,items:xt(e.items),linked_tests:xt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:iw(e.measurements),executions:sw(e.executions)};return zr(o),o}function cw(e){if(!(!Array.isArray(e)||e.length===0))return e.map(mw)}function gn(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 Vi(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qi(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function ul(e){if(!Vi(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!qi(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function dw(e){if(!Vi(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!qi(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function lw(e){let t=e?.trim().toLowerCase();if(!(!t||!Li.has(t)))return t}function uw(e){let t=e?.trim().toLowerCase();if(!(!t||!pl.has(t)))return t}function fw(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Vi(e))return{provenance_invalid:!0};let n=w(e.author),r=w(e.created_at),o=e.source_kind;return!n||!r||!he(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:w(e.source_ref)}}}function mw(e){let t={command:e.command?.trim()||void 0,path:e.path?Dt(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:lw(e.pm_context_mode),workspace_context_mode:uw(e.workspace_context_mode),...fw(e.provenance,e.provenance_invalid),updated_by:w(e.updated_by),updated_at:w(e.updated_at),env_set:ul(e.env_set),env_clear:gn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:gn(e.assert_stdout_contains),assert_stdout_regex:gn(e.assert_stdout_regex),assert_stderr_contains:gn(e.assert_stderr_contains),assert_stderr_regex:gn(e.assert_stderr_regex),assert_stdout_min_lines:xt(e.assert_stdout_min_lines),assert_json_field_equals:ul(e.assert_json_field_equals),assert_json_field_gte:dw(e.assert_json_field_gte),note:e.note?.trim()||void 0,phase:e.phase==="setup"?"setup":void 0};return zr(t),t}function pw(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Dt(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 w(e){if(typeof e!="string")return;let t=e.trim();return 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=w(r.id),i=w(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=w(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 hw(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=w(r.path);if(!o)continue;let i={path:Dt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=w(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function gw(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=w(r.command),i=w(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Dt(i));let a=w(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function yw(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=w(r.path);if(!o)continue;let i={path:Dt(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=w(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function bw(e){if(e===null||typeof e!="object")return;let t=e,n=w(t.id),r=w(t.title),o=w(t.status),i=o&&Ab.has(o)?o:void 0,s=Fr(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 d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return ww(d,t),d}function ww(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=w(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",_w],["files","files",hw],["tests","tests",gw],["docs","docs",yw]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function vw(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=bw(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function Ew(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=w(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=w(r.rationale);c&&(a.rationale=c);let d=w(r.evidence);d&&(a.evidence=d);let l=w(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function Ow(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=w(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=w(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function Sw(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=w(r.text);if(!o)continue;let i={text:o},s=w(r.command);s&&(i.command=s);let a=w(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function kw(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 Nt(e){let t=0;for(;t<e.length&&e[t]===`
|
|
4
|
+
`;)t+=1;return e.slice(t).trimEnd()}function Aw(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(dr.includes(t))return t}function Iw(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(cr.includes(t))return t}function yn(e){return e||void 0}function Tw(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))qi(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function Rw(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]=hn(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function Cw(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=bl(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length>0&&t.unknownFieldPolicy==="reject"&&Ce(`unknown schema fields are not allowed: ${r.join(", ")}`),r.length>0&&t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`)}function Hr(e,t={}){let n=gl(t),r=jr(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:nl(e.pm_format_version),source_type:w(e.source_type),type_options:kw(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Kb(e.dependencies),comments:Mi(e.comments),notes:Mi(e.notes),learnings:Mi(e.learnings),files:nw(e.files),tests:cw(e.tests),test_runs:rw(e.test_runs),docs:pw(e.docs),deadline:yn(e.deadline),reminders:Jb(e.reminders),events:Zb(e.events),closed_at:yn(e.closed_at),completed_at:yn(e.completed_at),assignee:w(e.assignee),claim_principal:w(e.claim_principal),source_owner:w(e.source_owner),author:yn(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,deferred_fields:il(e.deferred_fields),design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:w(e.definition_of_ready),order:e.order,goal:w(e.goal),objective:w(e.objective),value:w(e.value),impact:w(e.impact),outcome:w(e.outcome),why_now:w(e.why_now),parent:w(e.parent),reviewer:w(e.reviewer),risk:e.risk??void 0,confidence:Aw(e.confidence),sprint:w(e.sprint),release:w(e.release),blocked_by:w(e.blocked_by),blocked_reason:w(e.blocked_reason),unblock_note:w(e.unblock_note),reporter:w(e.reporter),severity:Iw(e.severity),environment:w(e.environment),repro_steps:w(e.repro_steps),resolution:w(e.resolution),expected_result:w(e.expected_result),actual_result:w(e.actual_result),affected_version:w(e.affected_version),fixed_version:w(e.fixed_version),component:w(e.component),regression:e.regression,customer_impact:w(e.customer_impact),close_reason:yn(e.close_reason),plan_mode:w(e.plan_mode),plan_scope:w(e.plan_scope),plan_harness:w(e.plan_harness),plan_resume_context:w(e.plan_resume_context),plan_steps:vw(e.plan_steps),plan_decisions:Ew(e.plan_decisions),plan_discoveries:Ow(e.plan_discoveries),plan_validation:Sw(e.plan_validation)};return Tw(i,e),Rw(i,n),Cw(i,n),zr(i),i}function wl(e){return We(e,ke)}function xw(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 Nw(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=xw(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 Dw(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 zi(e,t){return Hr(e,{...t,onWarning:void 0})}function Pw(e,t,n={}){let r=Dw(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=Nw(r.content);o||(e.trimStart().startsWith("{")&&bn("json_markdown","JSON front matter is not valid JSON"),bn("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{bn("json_markdown","JSON front matter is not valid JSON")}return yl(s,n.requireSupportedFormat),Ui(s,t),{metadata:zi(s,n),body:Nt(i)}}function $w(e,t,n={}){let r;try{r=Pi(e).value}catch{bn("toon","TOON item document is not valid TOON")}v(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(yl(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!hl.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&bn("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ui(o.front_matter,t),v(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:zi(o.front_matter,n),body:Nt(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return v(i===void 0||typeof i=="string","TOON item document body must be a string"),Ui(s,t),{metadata:zi(s,n),body:Nt(typeof i=="string"?i:"")}}function Mw(e,t={}){let n=Hr(e.metadata,t),r=wl(n),o=Nt(e.body??"");Bi(JSON.parse(JSON.stringify(r))),Bi({body:o});let i=JSON.stringify(r,null,2);return o?`${i}
|
|
6
|
+
|
|
7
|
+
${o}
|
|
8
|
+
`:`${i}
|
|
9
|
+
`}var jw=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function Hi(e,t){return typeof e=="string"?fl(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?ml(e.map((n,r)=>()=>Hi(n,`${t}[${r}]`))):ml(Object.entries(e).map(([n,r])=>()=>{let o=t?`${t}.${n}`:n;return fl(n,`${o} (key)`)??Hi(r,o)}))}function fl(e,t){let n=e.search(jw);return n<0?null:{path:t,index:n}}function ml(e){for(let t of e){let n=t();if(n!==null)return n}return null}function Bi(e){let t=Hi(e,"");if(t!==null)throw new y(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,g.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function Lw(e,t={}){let n=Hr(e.metadata,t),r=wl(n),o=Nt(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));Bi(s);let a=Ob(s),c;try{c=Pi(a).value}catch(d){throw new y("Refusing to persist a TOON item document that the configured decoder cannot read back.",g.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:d instanceof Error?d.message:String(d)})}if(!dl(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!dl(s[u],d[u]))??"document";throw new y(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,g.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:l,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 Lx(e,t={}){let n=Lr(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=gl(t);return r==="toon"?$w(e,o,t):Pw(e,o,t)}function Fx(e,t={}){return(t.format??"toon")==="toon"?Lw(e,t):Mw(e,t)}function Pt(e,t={}){return{metadata:Hr(e.metadata,t),body:Nt(e.body??"")}}import{AsyncLocalStorage as Fw}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]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var Wi=new Fw,vl=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Br(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Xe(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Br(n.id,128),o=Br(n.parent_id,128);if(r===void 0||!vl.test(r)||o!==void 0&&!vl.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Br(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function $t(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Br(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function Uw(e,t,n){let r=Wi.getStore(),o=$t({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Xe(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={...$t(r?.provenance),...o,...$t(e?.provenance)},a=Xe(e?.episode,!1)??Xe(n,!1)??i??Xe(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 Gi(e,t){return Uw(e.session_context,t,e.client_info?.episode)??{}}function Hx(e,t){let n=Wi.getStore(),r=Xe(e.episode,!0),o=Xe(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...$t(n?.provenance),...$t(e.provenance)};return Wi.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function Bx(e){let t=$t(e.provenance),n=Xe(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{createHash as P_}from"node:crypto";import{existsSync as gc,promises as $_,readFileSync as aT}from"node:fs";import ue from"node:path";import{constants as NI}from"node:fs";import H from"node:fs/promises";import F from"node:path";import{createHash as DI,randomUUID as Wo}from"node:crypto";import{existsSync as wI}from"node:fs";import{AsyncLocalStorage as c_}from"node:async_hooks";import Oe from"node:path";import{AsyncLocalStorage as Bm}from"node:async_hooks";import{realpathSync as bk}from"node:fs";import Ta from"node:path";import Mm from"fast-json-patch";import Nm from"node:fs/promises";import ik 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]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();import{AsyncLocalStorage as Qi}from"node:async_hooks";import{createHash as zw}from"node:crypto";import Q from"node:fs";import Al from"node:os";import Ze from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1ea9ada3-1c97-5787-9b6c-08aeaf825394")}catch{}})();var Zi=["model","effort","role","topic","version"],Wr=new Qi,Il=new Qi,Gr=new Qi,es=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Tl=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),Hw=Object.freeze({...Tl,max_bytes:4194304}),Ki=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Bw(e){let t=Ne(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?Hw:Tl,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var Rl=Object.freeze(es.filter(e=>e.harness!=="ci").map(Bw).sort((e,t)=>e.harness.localeCompare(t.harness))),Qe=new Map,Mt=new Map;function C(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function xe(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function Ne(e){let t=e.harness.trim().toLowerCase();if(!Ki.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:xe(e.environment_keys),model_environment_keys:xe(e.model_environment_keys),session_environment_keys:xe(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),xe(r)]).filter(([n])=>Ki.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"&&Ki.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:xe(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:xe(e.argv_markers).map(n=>n.toLowerCase()),client_names:xe(e.client_names).map(n=>n.toLowerCase())}}var Cl=es.map(Ne);function Vw(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qr(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(n=>n.length>0).includes(t)||e.trim().toLowerCase()===t}function ts(e=[]){let t=new Map(es.filter(o=>o.harness!=="ci").map(o=>[o.harness,Ne(o)]));for(let{adapter:o}of Qe.values())t.set(o.harness,Ne(o.descriptor));let n=[...t.values(),...Cl.filter(o=>o.harness==="ci"),...[...Mt.values()].map(o=>o.descriptor),...Gr.getStore()?.descriptors??[],...e.map(Ne)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function ns(e,t){for(let n of t??[]){let r=C(e[n]);if(r)return r.slice(0,256)}}function qw(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 xl(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 C(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return C(i.slice(s.length+1))?.slice(0,256)}}var Ww=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Je(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return Ww.has(n)?n:void 0}function Yi(e,t){return C(e?.[t])?.slice(0,256)}var Gw=1048576,Ji=4194304,Vr=new Map,El=Object.freeze({}),Xi=new Map,Ol=Object.freeze({});function Sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Kw(e){let t;try{t=JSON.parse(e)}catch{return Ol}let n=Sl(t);if(!n)return Ol;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=C(a.value.model)?.slice(0,256),s??=C(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Sl(c);d&&r.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function Nl(e){try{return Q.lstatSync(e).isFile()?"available":"missing"}catch(t){return me(t)?"missing":"failed"}}function Yw(e,t){let n;try{n=Q.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Ze.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:Nl(i)}})}catch(o){return{status:me(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function Dl(e,t){let n=C(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let r=Ze.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Ze.join(e.home_dir??Al.homedir(),".claude","projects"),i=Ze.join(o,r,`${n}.jsonl`),s=C(e.session_file),a=s&&Ze.basename(s)===`${n}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=Nl(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return Yw(o,n)}function Xw(e,t,n){let r=Dl(t,n);if(r.status==="available")try{let o=Q.openSync(r.path,Q.constants.O_RDONLY|Q.constants.O_NOFOLLOW);try{let i=Q.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=Xi.get(s);if(a)return a[e];let c=Math.min(i.size,Gw),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);Q.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&Q.readSync(o,f,0,l,i.size-l);let m={},p=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
|
|
11
|
+
`):[...u.toString("utf8").split(`
|
|
12
|
+
`).slice(0,4096),...f.toString("utf8").split(`
|
|
13
|
+
`).slice(-4096)];for(let _ of p){if(_.length===0||_.length>262144)continue;let b=Kw(_);if(m.model??=b.model,m.version??=b.version,m.model&&m.version)break}let h=Object.freeze(m);return Xi.clear(),Xi.set(s,h),h[e]}finally{Q.closeSync(o)}}catch{return}}function Jw(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=Q.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=Ze.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=r(c,i+1);if(d)return d}}};return r(e,0)}function Qw(e){if(e<=Ji)return[{offset:0,length:e}];let t=Math.floor(Ji/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function Zw(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=C(o?.model)?.slice(0,256),e.effort??=C(o?.effort)?.slice(0,256)}function ev(e,t){let n={},r=4096;for(let o of Qw(t)){let i=Buffer.alloc(o.length);Q.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
|
|
14
|
+
`).reverse().slice(0,r);r-=s.length;for(let a of s)if(Zw(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function tv(e,t,n){let r=C(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=Ze.join(t.home_dir??Al.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=Vr.get(i);if(s)return s[e];let a=Jw(o,r);if(!a){Vr.set(i,El);return}try{let c=Q.openSync(a,"r");try{let d=Q.fstatSync(c).size,l=ev(c,d);return Vr.set(i,l),l[e]}finally{Q.closeSync(c)}}catch{Vr.set(i,El);return}}function nv(e,t,n,r){let o=Gr.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(C(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=r?.provenance_resolvers[e];if(i==="claude_session_file")return Xw(e,t,n);if(i==="codex_session_file")return tv(e,t,n);if(i==="ai_agent_version"){let s=C(n.AI_AGENT);return!s||!r||!qr(s,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function rv(e,t,n,r){if(e==="ai_agent_version"){let o=C(r.AI_AGENT);return o!==void 0&&qr(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?C(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":Dl(n,r).status}function rs(e){return e||(Il.getStore()??{env:process.env,argv:process.argv})}function ov(e,t,n,r){let o=e.environment_keys.some(a=>C(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return qr(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||qr(r,a));return o||i||s}function iv(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 sv(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function av(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Zi,...Object.keys(r?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=Je(e,C(n[s])?.slice(0,256)),l=Je(e,xl(t.argv??[],e)),d=Je(e,qw(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=Yi(o?.provenance,e),p=Je(e,ns(n,u[e])),h=Je(e,Yi(f,e)),_=Je(e,Yi(t.provenance,e)),b=nv(e,t,n,r);return sv([[c,"override"],[m,"session"],[l,"argv"],[p,"environment"],[h,"mcp_client"],[_,"host"],[b,"probe"]])??iv(e,i)??(d?{value:d,source:"argv"}:void 0)}function cv(e,t){if(!(!e||!t))return zw("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function dv(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Zi,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let d=av(c,e,t,n,r,o);d?a[c]=d:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function tN(e){let t=e.map(Ne),n=new Map(Cl.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=Mt.get(i.harness);if(s&&!Vw(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=Mt.get(i.harness);Mt.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Mt.get(i.harness);!s||s.registrations<=1?Mt.delete(i.harness):s.registrations-=1}}}}function lv(e){let t=Ne(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=C(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>Ji||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(xe(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function nN(){let e=new Map(Rl.map(t=>[t.harness,t]));for(let{adapter:t}of Qe.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function rN(e){let t=e.map(lv),n=new Map(Rl.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=Qe.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=Qe.get(i.harness);Qe.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Qe.get(i.harness);!s||s.registrations<=1?Qe.delete(i.harness):s.registrations-=1}}}}function oN(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function iN(e,t){return Il.run(e,t)}function sN(e,t,n={}){let r=e.map(Ne);return ts(r),Gr.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function os(e){let t=rs(e),n=t.env??{},r=ts(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(p=>p.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(p=>ov(p,n,o,i)),a=Gi(t,n),c=[ns(n,s?.session_environment_keys),C(t.client_info?.session)?.slice(0,256)].find(p=>p!==void 0),d=cv(s?.harness,c),l=kl({cwd:t.cwd??process.cwd(),env:n,key:d}),u=dv(t,n,s,a,l),f=u.model,m=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",d],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(m.filter(p=>p[1]!==void 0))}function uv(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function fv(e,t,n,r,o,i,s){let a=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=rv(a,n,r,o);return{...uv(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function Pl(e){let t=rs(e),n=os(t),r=ts(t.descriptors).find(d=>d.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&Gr.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(C(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Gi(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,ns(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,xl(t.argv??[],"role")].some(d=>{let l=C(d)?.slice(0,256);return l!==void 0&&Je("role",l)===void 0}),c=Object.fromEntries(Zi.map(d=>[d,fv(d,n,r,t,o,i,d==="role"&&a)]));return{...n,provenance_outcomes:c}}function aN(){return process.env.PM_AUTHOR}function cN(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function dN(e){return os(e).harness}function mv(e,t,n){let r=rs(n),o=os(r);if(e!==void 0){let s=C(e);return Rt(s,"--author"),s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=C(r.env.PM_AUTHOR);return Rt(s,"PM_AUTHOR"),s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=C(t);return i?(Rt(i,"default_author"),{author:i,source:"configured",...o}):o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function $l(e){let t=Wr.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Ml(e){let t=Wr.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 lN(e){let t=Wr.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function uN(e,t){let n=mv(e,t);return Wr.enterWith(n),n.author}import k from"node:fs/promises";import T from"node:path";import{createHash as no,randomUUID as Os}from"node:crypto";import{createRequire as Wv}from"node:module";import{setImmediate as ru}from"node:timers/promises";import jl 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]="2560e353-1428-540b-bf0b-3c157bdb3b3b")}catch{}})();async function Kr(e,t){let n=await jl.readFile(e).catch(r=>{if(me(r))return null;throw r});return is(e,t,n)}async function bN(e,t){let n=await jl.open(e,"r").catch(r=>{if(me(r))return null;throw r});if(n===null)return{...await is(e,t,null),source:null};try{let r=await n.stat({bigint:!0}),o=await n.readFile();return{...await is(e,t,o),source:r}}finally{await n.close()}}async function is(e,t,n){let r=n?.toString("utf8")??null;if(r===null)return{raw:r,raw_bytes:n,entries:[]};if(await Yr({path:e,scope:"project"}),r.trim()==="")return{raw:r,raw_bytes:n,entries:[]};let o=Lr(r);if(o)throw new y(`History for ${t} contains merge conflict markers at line ${o.line} (${o.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.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 i=[];for(let[s,a]of r.split(/\r?\n/).entries()){let c=a.trim();if(!c)continue;let d;try{d=JSON.parse(c)}catch{throw new y(`History for ${t} contains invalid JSON at line ${s+1}. Repair or restore the history stream and retry.`,g.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}let l=pv(d);if(l!==null)throw new y(`History for ${t} holds ${l} at line ${s+1}, which is not a history record. Remove or restore the line and retry.`,g.GENERIC_FAILURE,{code:"history_record_invalid",item_id:t,reason:l,details:{line:s+1},required:"Every history line must be one JSON object record.",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run: it removes a line that cannot hold a record (a JSON null, boolean or number) and keeps every record.`,"Otherwise recover the line from version control or a backup."]});i.push(d)}return{raw:r,raw_bytes:n,entries:i}}function pv(e){return e===null?"a JSON null":Array.isArray(e)?"a JSON array":typeof e=="object"?null:`a JSON ${typeof e}`}function wN(e){return e===null||typeof e=="boolean"||typeof e=="number"}async function vN(e,t){return(await Kr(e,t)).entries}import us 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]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function Ll(e){let t=[],n=e[0]?.op==="history_compact_baseline",r=n?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(r!==void 0&&t.push({prior_genesis_index:r,repeated_create_index:i+1,sequence:o?"delete_then_create":n?"checkpoint_then_create":"multiple_creates"}),r??=i+1,o=!1);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]="01a75358-2a0c-531d-bf79-ff353e1990c9")}catch{}})();var _v=1;function hv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&typeof t.gap_from=="string"&&typeof t.gap_to=="string"&&t.gap_from!==t.gap_to&&(t.record_hash===null||typeof t.record_hash=="string")}function Xr(e){if(!Object.hasOwn(e,"bridge"))return;let t=e.bridge;if(e.op!=="history_repair"||typeof e.record_hash!="string"||typeof t!="object"||t===null||Array.isArray(t))return"invalid";let n=t;return n.version===_v&&Object.keys(n).length===3&&typeof n.segment_digest=="string"&&Array.isArray(n.breaks)&&n.breaks.length>0&&[...n.breaks].every(hv)?n:"invalid"}function kN(e,t){return{gap_from:e.after_hash,gap_to:t.before_hash,record_hash:t.record_hash??null}}function as(e,t,n){return e!==void 0&&e.gap_from===t.after_hash&&e.gap_to===n.before_hash&&e.record_hash===(n.record_hash??null)}function cs(e,t){return ce(ss(e),re(t.hash_algorithm))}var gv=/^(?:0|[1-9]\d*)$/u,Fl=e=>gv.test(e)&&Number(e)<2**32-1;function ss(e){if(Array.isArray(e))return`[${e.map(r=>ss(r??null)).join(",")}]`;if(e===null||typeof e!="object")return JSON.stringify(e);let t=e,n=Object.keys(t).filter(r=>t[r]!==void 0);return`{${[...n.filter(Fl),...n.filter(r=>!Fl(r)).sort()].map(r=>`${JSON.stringify(r)}:${ss(t[r])}`).join(",")}}`}function Ul(e,t){for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(e[n],"bridge"))return n;return-1}function yv(e,t){try{return cs(e,t)}catch{return null}}function bv(e,t,n,r){let o=t.breaks[0],i=-1;for(let s=Math.max(1,n);s<r;s+=1){let a=e[s],c=e[s-1].after_hash===o.gap_from&&a.before_hash===o.gap_to,d=o.record_hash!==null&&a.record_hash===o.record_hash;if(!c&&!d)continue;let l=e.slice(s,r);if(yv(l,e[r])===t.segment_digest)return{start:s,digest:!0};i<0&&c&&l.every(u=>u.replay_inexact===!0)&&(i=s)}return{start:i,digest:!1}}function ds(e){let t={segments:[],unlocated:[],undigested:[]},n=1;return e.forEach((r,o)=>{if(!Object.hasOwn(r,"bridge"))return;let i=Xr(r),s=typeof i=="object"?bv(e,i,n,o):{start:-1,digest:!1},a=s.start;a<0?t.unlocated.push(o):s.digest||t.undigested.push(o),t.segments.push({start:a<0?n:a,end:o,exact:a>=0}),a>=0&&(n=o+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]="b329322c-71f1-57f9-b678-5e1166ecb938")}catch{}})();var vv={metadata:{},body:""};function Bl(){return structuredClone(vv)}function MN(e,t=et,n){return Jr(e,t,n)[0]}function Jr(e,t,n){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return eu(Vl(e),t,n)}catch{}let r=ce(A({replay_fallback:!0,metadata:e.metadata,body:e.body}),n);return t===2?[r,r]:[r]}function fs(e,t,n,r,o){let i=re(r.hash_algorithm),s=`${n}:${i}`,a=o?.before.get(s)??Jr(e,n,i),c=Jr(t,n,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===r.before_hash&&c[l]===r.after_hash),beforeIndex:a.indexOf(r.before_hash),afterIndex:c.indexOf(r.after_hash)}}function Vl(e){return{metadata:e.metadata,body:e.body}}function jN(e,t={}){return Pt(Vl(e),t)}function LN(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=Pt(e);return{metadata:We(t.metadata,ke),body:t.body}}function Qr(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function ql(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Wl(e){return Array.isArray(e)?e.filter(ql).map(t=>({...t,...(t.op==="add"||t.op==="replace")&&Object.hasOwn(t,"value")?{value:structuredClone(t.value)}:{},path:Qr(t.path),from:typeof t.from=="string"?Qr(t.from):void 0})):[]}function Ev(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 ms(e,t){try{let n=Wl(t),r=us.applyPatch(structuredClone(e),n,!0,!0).newDocument;return Ev(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 Ov(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&En.includes(t)))]}function Gl(e){return e!==void 0&&!En.includes(e)}function Kl(e,t){return e!==void 0?[e]:t===void 0?[...En]:[t]}function Yl(e){let t=Zr(e);if(!t.ok)return t.error;let n=gs(e);return n.ok?void 0:n.error}function ps(e,t){let n=Yl(e);if(n)return{ok:!1,error:n};let r=ms(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function Sv(e,t){let n=Yl(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function kv(e,t,n,r,o){let i=[];for(let s of n){let a=fs(e,t,s,r,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function _s(e){if(!Zl(e))return!1;let t;try{t=re(e.hash_algorithm)==="sha512"?128:64}catch{return!1}let n=new RegExp(`^[a-f0-9]{${t}}$`,"u");return!n.test(e.before_hash)||!n.test(e.after_hash)?!1:!e.patch.filter(ql).map(r=>({op:r.op,path:Qr(r.path),from:typeof r.from=="string"?Qr(r.from):void 0})).every(r=>Av(r))||e.before_hash===e.after_hash||Object.hasOwn(e,"bridge")}function Av(e){return e.op==="test"?!0:e.from!==e.path?!1:e.op==="move"||e.op==="copy"&&!/\/(?:\d+|-)$/u.test(e.path)}var Xl=new WeakMap;function Iv(e,t){if(t===0||!_s(e[t]))return;let n=Ul(e,t);if(n<0)return;let r=Xr(e[n]);if(!(typeof r!="object"||!as(r.breaks[0],e[t-1],e[t])))return{start:t,closer:n,bridge:r,next:1}}function Tv(e,t,n,r,o){let i=e[t],s=e[t-1];if(!_s(i))return{ok:!1,error:"record_incomplete"};let a=ps(i,r);if(!a.ok)return a;let c=o.map(d=>fs(r,a.document,d,i));return c.some(d=>d.beforeIndex>=0)&&!c.some(d=>d.pairIndex>=0)?{ok:!1,error:"after_hash_mismatch"}:i.before_hash===s.after_hash?a:as(n.bridge.breaks[n.next],s,i)?(n.next+=1,a):{ok:!1,error:"bridge_unnamed_break"}}function Rv(e,t,n,r,o){let i=e[t];if(!_s(i))return{ok:!1,error:"record_incomplete"};let s=ps(i,r);if(!s.ok)return s;if(n.next!==n.bridge.breaks.length)return{ok:!1,error:"bridge_names_absent_break"};if(i.before_hash!==e[t-1].after_hash)return{ok:!1,error:"bridge_link_mismatch"};if(cs(e.slice(n.start,t),i)!==n.bridge.segment_digest)return{ok:!1,error:"bridge_segment_mismatch"};let a=re(i.hash_algorithm),c=o.find(d=>Jr(s.document,d,a).includes(i.after_hash));return c===void 0?{ok:!1,error:"bridge_after_hash_mismatch"}:{ok:!0,document:s.document,version:c}}function Jl(e,t,n,r,o){e.replay=r,e.beforeHashMemo=o,e.detectedVersion=n,e.authoritativeExplicitVersion=t.item_hash_version??e.authoritativeExplicitVersion}function Cv(e,t,n){let r=n.segment,o=e[t];if(t===r.closer&&n.authoritativeExplicitVersion!==void 0&&o.item_hash_version!==n.authoritativeExplicitVersion)return"bridge_epoch_mismatch";let i=(t<r.closer?Tv:Rv)(e,t,r,n.replay,Kl(o.item_hash_version,n.authoritativeExplicitVersion));if(!i.ok)return i.error;if(i.version===void 0){n.replay=i.document,n.beforeHashMemo=new Map,n.authoritativeExplicitVersion=o.item_hash_version??n.authoritativeExplicitVersion;return}let s={start:r.start,end:t};Xl.set(s,i.version),n.bridgedSegments.push(s),n.segment=void 0,Jl(n,o,i.version,i.document,new Map)}function xv(e,t,n,r){let o=e[t];if(Object.hasOwn(o,"bridge"))return"bridge_without_break";let i=ps(o,n.replay);if(!i.ok)return i.error;if(r){n.replay=i.document,n.beforeHashMemo=new Map,n.detectedVersion=void 0,n.authoritativeExplicitVersion=void 0;return}let s={before:n.beforeHashMemo,after:new Map},a=kv(n.replay,i.document,Kl(o.item_hash_version,n.authoritativeExplicitVersion),o,s),c=a.find(({match:l})=>l.pairIndex>=0);if(c!==void 0){Jl(n,o,c.version,i.document,s.after);return}let d=a.some(({match:l})=>l.beforeIndex>=0);if(n.segment=d?void 0:Iv(e,t),n.segment===void 0)return`${d?"after":"before"}_hash_mismatch`;n.replay=i.document,n.beforeHashMemo=new Map,n.authoritativeExplicitVersion=o.item_hash_version??n.authoritativeExplicitVersion}function vn(e){let t={replay:Bl(),beforeHashMemo:new Map,bridgedSegments:[]},n=Ll(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`),r=(s,a)=>({ok:s,errors:s?[]:n,...a,...t.bridgedSegments.length===0?{}:{bridged_segments:t.bridgedSegments}}),o=(s,a)=>(n.push(`verify_failed:${s}:entry_${a+1}`),r(!1,{})),i=e.findIndex(s=>Xr(s)==="invalid");if(i>=0)return o("bridge_invalid",i);for(let s=0;s<e.length;s+=1){let a=e[s].item_hash_version,c=Gl(a);c&&n.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${s+1}`);let d=t.segment===void 0?xv(e,s,t,c):Cv(e,s,t);if(d!==void 0)return o(d,s)}return r(n.length===0,t.detectedVersion===void 0?{}:{item_hash_version:t.detectedVersion})}function FN(e){let t=vn(e);return{ok:t.ok,errors:t.errors}}function ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zl(e,t,n){try{let r=us.applyPatch(structuredClone(e),[t],!0,!1).newDocument;return n&&!ls(r)?{ok:!1}:{ok:!0,document:r}}catch{return{ok:!1}}}function Hl(e,t,n){let r=structuredClone(e),o=0,i=0;for(let s of Wl(t)){let a=zl(r,s,n);if(a.ok){r=a.document;continue}if(s.op==="replace"){let c=zl(r,{...s,op:"add"},n);if(c.ok){r=c.document,o+=1;continue}}i+=1}return{working:r,convertedReplaceToAdd:o,skippedOps:i}}function Nv(e,t,n){let r=Hl(e,t,!1);if(!ls(r.working)&&n==="delete")return{document:{metadata:{},body:""},convertedReplaceToAdd:r.convertedReplaceToAdd,skippedOps:r.skippedOps};let{working:o,convertedReplaceToAdd:i,skippedOps:s}=ls(r.working)?r:Hl(e,t,!0),a=o;return{document:{metadata:typeof a.metadata=="object"&&a.metadata!==null?a.metadata:{},body:typeof a.body=="string"?a.body:e.body},convertedReplaceToAdd:i,skippedOps:s}}function Dv(e){let t=Ov(e);if(t.length===1)return t[0];let n=vn(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:et}function Pv(e,t,n=t.patch){let r=ms(e,n);if(r.ok)return{next:r.document,patch:n,repaired:A(n)!==A(t.patch),converted:0,skipped:0};let o=Nv(e,n,t.op);return{next:o.document,patch:us.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function $v(e,t,n){return Pv(e,t,n.projectPatch?.(t,e))}function Mv(e,t,n,r){let o=vn(e),i=t.projectPatch===void 0&&t.continuousHashSurface!==!0?(o.bridged_segments??[]).filter(s=>Xl.get(s)===n&&(!r||e[s.end].item_hash_version===n)&&e.slice(s.start,s.end+1).every(a=>a.item_hash_version===void 0||a.item_hash_version===n)):[];return{inputVerifies:o.ok,preservable:new Map(i.map(s=>[s.start,s.end])),inexact:Ql(t.callerMarksBridgeCoverage===!0?[]:ds(e).segments)}}function Ql(e){let t=new Set;for(let{start:n,end:r,exact:o}of e){let i=o===!1?r:r-1;for(let s=n;s<=i;s+=1)t.add(s)}return t}function jv(e){return hs(e,{...e,replay_inexact:!0},{retainPriorRecord:!0,retainPriorRecordHash:!1})}function UN(e){let t=Ql(ds(e).segments);return e.map((n,r)=>t.has(r)&&n.replay_inexact!==!0?jv(n):n)}function Lv(e,t,n,r,o,i){let s=r;for(let a=t;a<=n;a+=1){let c=e[a],d=ms(s,c.patch);if(!d.ok)throw new TypeError(`patch_apply_failed:entry_${a+1}`);s=d.document,o.push(c),i.push({index:a+1,rehashed:!1,patch_repaired:!1,converted_replace_to_add:0,skipped_ops:0})}return s}function Fv(e,t,n){n.itemHashVersion===void 0?delete t.item_hash_version:t.item_hash_version=n.itemHashVersion,n.inexact&&(t.replay_inexact=!0);let r=Object.hasOwn(e,"bridge");delete t.bridge;let o=r||t.replay_inexact!==e.replay_inexact,i=n.rehashed||n.patchRepaired||o||t.item_hash_version!==e.item_hash_version;return{changed:i,persist:n.inputVerifies?o:i,anchorsChanged:n.rehashed||n.patchRepaired,entry:i?hs(e,t,{retainOriginalPatch:n.patchRepaired,retainPriorRecord:r}):t}}function zN(e,t=Dv(e),n={}){let r=e.findIndex(_=>Gl(_.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=Bl(),i=[],s=[],a=0,c=0,d=0,l=0,u=0,f,m=t!==1||e.some(_=>_.item_hash_version!==void 0),p=Mv(e,n,t,m),h=!0;for(let _=0;_<e.length;_+=1){let b=e[_];Sv(b,_);let E=h?p.preservable.get(_):void 0;if(E!==void 0){o=Lv(e,_,E,o,i,s),_=E;continue}let j=$v(o,b,n),{next:X,patch:Se,repaired:Jo,converted:kc,skipped:Ac}=j;d+=kc,l+=Ac,c+=Number(Jo);let Ve=fs(o,X,t,b);f===void 0||n.continuousHashSurface!==!0?f=[Ve.pairIndex,Ve.beforeIndex,Ve.afterIndex,Math.min(f??0,Ve.beforeHashes.length-1)].find(L_=>L_>=0):f=Math.min(f,Ve.beforeHashes.length-1);let Ic=Ve.beforeHashes[f],Tc=Ve.afterHashes[f],Qo=Ic!==b.before_hash||Tc!==b.after_hash;Qo&&(a+=1);let Zo=Fv(b,{...b,patch:Se,before_hash:Ic,after_hash:Tc},{itemHashVersion:m?t:void 0,rehashed:Qo,patchRepaired:Jo,inexact:p.inexact.has(_),inputVerifies:p.inputVerifies});h&&=!Zo.anchorsChanged,u+=Number(Zo.persist),i.push(Zo.entry),s.push({index:_+1,rehashed:Qo,patch_repaired:Jo,converted_replace_to_add:kc,skipped_ops:Ac}),o=X}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,entriesResealed:u,details:s,itemHashVersion:t,explicitItemHashVersion:m}}function HN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
15
|
+
`)}
|
|
16
|
+
`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var Uv=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],zv=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],Hv=new Set(Uv),Bv=new Set(zv),Vv=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function qv(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function jt(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:Hv.has(e.op)?"maintenance":Bv.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=qv(t);return n!==void 0&&Vv.has(n)})?"maintenance":"substantive"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function tu(e){let t=process.emitWarning;process.emitWarning=(n,...r)=>{n==="SQLite is an experimental feature and might change at any time"&&r[0]==="ExperimentalWarning"||Reflect.apply(t,process,[n,...r])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function nu(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?tu(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]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();var Gv="history-event-index.sqlite",Ss="7",Kv=8,ou=32,fu="history-event-index",Yv="history-event-index:append:",Xv=5e3,ks=300,mu=3e4,Jv="history-event-index-invalidation",Qv="history-event-index-invalidations",Zv=ks*2*1e3,De=Symbol("history-index-changed"),tt=new Map;function rt(e){return T.join(e,"runtime",Gv)}function pu(e){return T.join(e,"runtime","history-event-index-repair-deferred")}async function _u(e){try{let t=Number(await k.readFile(pu(e),"utf8")),n=Date.now()-t;return n>=0&&n<Xv}catch{return!1}}async function iu(e){try{await k.writeFile(pu(e),`${Date.now()}
|
|
17
|
+
`)}catch{}}function An(e){return T.join(e,"runtime",Qv)}async function ro(e){let t=await k.readdir(An(e)).catch(n=>{if(B(n))return[];throw n});return{pending:t.filter(n=>n.endsWith(".pending")).sort(),committed:t.filter(n=>n.endsWith(".committed")).sort()}}async function su(e){let t=await ro(e);return{pending:(await Promise.all(t.pending.map(async n=>{let r=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(n);if(r!==null){let o=r[2];if(await Sn({pid:Number(r[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(r[3])),Zv))return n}return await k.rm(T.join(An(e),n),{force:!0}),null}))).filter(n=>n!==null),committed:t.committed}}async function vs(e,t,n=mu){let r=await kn(e,Jv,ks,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await r()}}async function eE(e){let t=An(e);await k.mkdir(t,{recursive:!0});let n=Os(),r=await On(),o=T.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await k.writeFile(o,`pending
|
|
18
|
+
`,{flag:"wx"}),{pendingPath:o,committedPath:T.join(t,`${n}.committed`)}}function tE(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}async function oo(e){try{await k.rm(rt(e),{force:!0})}catch{}}async function ys(e,t){let n=An(e);await k.mkdir(n,{recursive:!0}),await k.writeFile(T.join(n,`${Os()}${t?".contended":""}.committed`),`committed
|
|
19
|
+
`,{flag:"wx"}),t||await oo(e)}function io(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function Es(e,t){let n;try{return n=new t(rt(e)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return nt(r)}finally{n?.close()}}async function au(e,t){return t.pending.length>0||await uu(e,fu,Yv)}async function hu(e,t,n=mu,r="rebuild"){let o=await kn(e,fu,ks,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function gu(e,t,n=!1){let r=T.join(e,"history"),o=await k.readdir(r,{withFileTypes:!0}).catch(u=>{if(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT")return[];throw u}),i=tt.get(e)??{streams:new Map,ordered_events:[]},s=new Map(i.streams),a=i.ordered_events,c=new Set,d=!tt.has(e);for(let u of o.filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).sort((f,m)=>f.name.localeCompare(m.name))){let f=u.name.slice(0,-6);c.add(f);let m=T.join(r,u.name);if(!bs(f,t))continue;let p=await rE(m,f,s.get(f),n);p!==void 0&&(s.set(f,p),d=!0)}for(let u of s.keys())c.has(u)||(s.delete(u),d=!0);d&&(a=[...s.values()].flatMap(u=>u.events).sort(As));let l={streams:s,ordered_events:a};if(tt.delete(e),tt.set(e,l),tt.size>Kv){let u=tt.keys().next().value;tt.delete(u)}return{events:l.ordered_events.filter(u=>bs(u.stream_id,t)).map(u=>nE(u,n)),stream_receipts:new Map([...l.streams].filter(([u])=>bs(u,t)).map(([u,f])=>[u,{byte_size:f.byte_size,content_hash:f.signature}]))}}function nE(e,t){return t||e.recorded_entry===void 0?e:{stream_id:e.stream_id,stream_offset:e.stream_offset,entry:e.entry}}function bs(e,t){return!t?.length||t.includes(e)}async function rE(e,t,n,r){if(!r&&n!==void 0&&n.byte_size===(await k.stat(e)).size){let o=no("sha256").update(await k.readFile(e)).digest("hex");if(n.signature===o)return}return oE(e,t,r)}async function oE(e,t,n){let r=await Kr(e,t);if(n){let i=vn(r.entries);if(!i.ok)throw new y(`Authoritative history integrity verification failed for ${t}.`,g.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${t} --verify to inspect the authoritative chain before retrying.`]})}let o=r.raw_bytes??new Uint8Array;return{signature:no("sha256").update(o).digest("hex"),byte_size:o.byteLength,events:yu(r.entries,t).map((i,s)=>({stream_id:t,stream_offset:s,entry:i,...n?{recorded_entry:r.entries[s]}:{}}))}}async function iE(e,t){return yu((await Kr(e,t)).entries,t)}function yu(e,t){for(let[n,r]of e.entries())if(typeof r.ts!="string"||!Tt(r.ts.trim()))throw new y(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,g.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return e.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}var ws;function ao(){return ws!==void 0||(ws=nu(process.versions.node,Wv(import.meta.url))),ws}function sE(e){e.exec(`
|
|
20
|
+
PRAGMA journal_mode = OFF;
|
|
21
|
+
PRAGMA synchronous = OFF;
|
|
22
|
+
CREATE TABLE metadata (
|
|
23
|
+
key TEXT PRIMARY KEY,
|
|
24
|
+
value TEXT NOT NULL
|
|
25
|
+
) STRICT;
|
|
26
|
+
CREATE TABLE events (
|
|
27
|
+
stream_id TEXT NOT NULL,
|
|
28
|
+
stream_offset INTEGER NOT NULL,
|
|
29
|
+
ts TEXT NOT NULL,
|
|
30
|
+
author TEXT NOT NULL,
|
|
31
|
+
agent_harness TEXT,
|
|
32
|
+
agent_instance TEXT,
|
|
33
|
+
op TEXT NOT NULL,
|
|
34
|
+
event_class TEXT NOT NULL CHECK(event_class IN ('substantive', 'maintenance')),
|
|
35
|
+
entry_json TEXT NOT NULL,
|
|
36
|
+
PRIMARY KEY(stream_id, stream_offset)
|
|
37
|
+
) STRICT;
|
|
38
|
+
CREATE TABLE streams (
|
|
39
|
+
stream_id TEXT PRIMARY KEY,
|
|
40
|
+
byte_size INTEGER NOT NULL CHECK(byte_size >= 0),
|
|
41
|
+
content_hash TEXT NOT NULL
|
|
42
|
+
) STRICT;
|
|
43
|
+
CREATE INDEX events_order
|
|
44
|
+
ON events(ts, stream_id, stream_offset);
|
|
45
|
+
CREATE INDEX events_op_order
|
|
46
|
+
ON events(op, ts, stream_id, stream_offset);
|
|
47
|
+
CREATE INDEX events_class_stream_order
|
|
48
|
+
ON events(event_class, stream_id, ts, stream_offset);
|
|
49
|
+
CREATE INDEX events_author_order
|
|
50
|
+
ON events(author, ts, stream_id, stream_offset);
|
|
51
|
+
CREATE INDEX events_harness_order
|
|
52
|
+
ON events(agent_harness, ts, stream_id, stream_offset);
|
|
53
|
+
CREATE INDEX events_instance_order
|
|
54
|
+
ON events(agent_instance, ts, stream_id, stream_offset);
|
|
55
|
+
`),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Ss)}function bu(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
|
|
56
|
+
stream_id, stream_offset, ts, author, agent_harness,
|
|
57
|
+
agent_instance, op, event_class, entry_json
|
|
58
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,jt(n),JSON.stringify(n))}function wu(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!Tt(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function vu(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
|
|
59
|
+
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(t,n.byte_size,n.content_hash)}async function aE(e,t={}){let n=ao();return n?hu(e,async()=>{let r;try{r=await vs(e,()=>su(e),t.lockWaitMs)}catch(a){if(a instanceof y&&a.code==="lock_conflict")return!1;throw a}if(r.pending.length>0||io(r)&&Es(e,n))return!1;let o=rt(e);await k.mkdir(T.dirname(o),{recursive:!0});let i=`${o}.${Os()}.tmp`,s;try{s=new n(i),sE(s),s.exec("BEGIN IMMEDIATE");let a=await gu(e);await cE(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await vs(e,async()=>{let d=await su(e);return d.pending.length>0||!tE(r.committed,d.committed)||io(d)&&Es(e,n)?!1:(await k.rm(o,{force:!0}),await k.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(r.committed.map(d=>k.rm(T.join(An(e),d),{force:!0}))),c||(await iu(e),await k.rm(i,{force:!0})),c}catch(a){throw await iu(e),s?.close(),await k.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function cE(e,t){let n=0;for(let r of t.events)bu(e,r),++n%500===0&&await ru();for(let[r,o]of t.stream_receipts)vu(e,r,o),++n%500===0&&await ru()}function eo(e,t){return!t||t.length===0||t.includes(e)}function As(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function so(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function dE(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(As(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:so(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<so(t.since_ts))return!1;return!0}function lE(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function uE(e,t){return!dE(e,t)||!eo(e.entry.op,t.ops)||!eo(e.entry.author,t.authors)||!eo(e.entry.agent_instance??"",t.agent_instances)||!eo(e.stream_id,t.stream_ids)||!lE(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function fE(e,t){let n=Math.max(0,Math.floor(t.limit)),r=await gu(e,t.stream_ids,t.verify),o=r.events.filter(i=>uE(i,t)).slice(0,n+1);return{events:o.slice(0,t.limit),has_more:o.length>t.limit,...t.verify?{verified_streams:r.stream_receipts.size}:{}}}async function mE(e,t){let n=e.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(T.basename(t,".jsonl")),r=0;try{r=(await k.stat(t)).size}catch(i){if(!B(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;let o=await Ts(T.dirname(T.dirname(t)),T.basename(t,".jsonl"));return n===void 0?o?.byte_size===0:o?.content_hash===n.content_hash}async function Eu(e,t,n){let r=T.dirname(T.dirname(e)),o=ao(),i=!1,s=async()=>{await n(),i=!0};if(!o){await cu(r,s);return}try{await hu(r,async()=>{let a=rt(r);try{await k.access(a)}catch{await s();return}let c;try{if(c=new o(a),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Ss)throw new TypeError("Unsupported history event index version");if(!await mE(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),nt(l))throw l;await ys(r,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),nt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await ys(r,!1),await s();return}let d=!1;try{await s(),d=!0;let l=T.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);bu(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),vu(c,l,await Ts(r,l)),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await ys(r,nt(l))}},0,"append")}catch(a){if(i){await oo(r);return}if(!_E(a))throw a;await cu(r,s,nt(a))}}async function cu(e,t,n=!1){let r=!1,o;try{await vs(e,async()=>{let i=n||io(await ro(e)),s=await eE(e);o=s.pendingPath;try{await t(),r=!0}catch(a){throw await k.rm(s.pendingPath,{force:!0}),a}await k.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await oo(e)})}catch(i){if(r){await oo(e);try{await k.rm(o,{force:!0})}catch{}return}throw i}}async function Is(e){await k.rm(rt(T.dirname(T.dirname(e))),{force:!0})}function to(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function pE(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function Ou(e,t,n,r){let o;try{let i=await ro(e);if(await au(e,i))return De;let s=await du(e);if(i.committed.length>0)return io(i)&&Es(e,t)?De:null;if(o=new t(rt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Ss)return null;let a=r(o);if(a===null)return null;let c=hE(o,n),d=o;o=void 0,d.close();let l=await yE([...c.keys()],e,n),u=await gE(c,e,l),f=await ro(e);return f.committed.length>0||await au(e,f)||s!==await du(e)?De:u?a:null}catch(i){return nt(i)?De:null}finally{o?.close()}}function nt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function _E(e){return nt(e)||e instanceof y&&e.code==="lock_conflict"}function hE(e,t){let n=new Map,r=t&&t.length>0?[...new Set(t)]:void 0;if(r===void 0)for(let o of e.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(o.stream_id),{byte_size:Number(o.byte_size),content_hash:String(o.content_hash)});else for(let o=0;o<r.length;o+=500){let i=r.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)})}return n}async function du(e){let t=await k.stat(rt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function sD(e,t){if(t.verify)return{result:await fE(e,t),repair_needed:!1};let n=ao();if(!n)return{result:null,repair_needed:!1};let r=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=so(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(r.push("ts >= ?"),o.push(so(t.since_ts)));to(r,o,"op",t.ops),to(r,o,"author",t.authors),pE(r,o,t.harnesses,t.harness_alias_authors),to(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);to(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s=await Ou(e,n,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
60
|
+
FROM events${i}
|
|
61
|
+
ORDER BY ts, stream_id, stream_offset
|
|
62
|
+
LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(wu);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===De?null:s,repair_needed:s===null&&!await _u(e)}}function Su(e,t){let n=Object.create(null);for(let r of e){if(!t.has(r.stream_id)||jt(r.entry)!=="substantive")continue;let o=n[r.stream_id];(o===void 0||As(o,r)<0)&&(n[r.stream_id]=r)}return n}async function Ts(e,t){if(T.basename(t)!==t)return null;try{let n=T.join(e,"history",`${t}.jsonl`),r=await k.stat(n),o=await k.readFile(n);return r.size!==o.length?null:{byte_size:o.length,content_hash:no("sha256").update(o).digest("hex")}}catch(n){if(B(n))return{byte_size:0,content_hash:no("sha256").digest("hex")};throw n}}async function gE(e,t,n){for(let r=0;r<n.length;r+=ou){let o=n.slice(r,r+ou),i=await Promise.all(o.map(s=>Ts(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a.byte_size===0&&d===void 0)&&(a.byte_size!==d?.byte_size||a.content_hash!==d.content_hash))return!1}}return!0}async function yE(e,t,n){if(n&&n.length>0)return[...new Set(n.filter(o=>o.trim().length>0))];let r=await k.readdir(T.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(B(o))return[];throw o});return[...new Set([...e,...r])]}async function lu(e,t,n,r){return e?Ou(t,e,n,o=>{let i=[];for(let s=0;s<n.length;s+=500){let a=n.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
63
|
+
FROM (
|
|
64
|
+
SELECT stream_id, stream_offset, entry_json,
|
|
65
|
+
ROW_NUMBER() OVER (
|
|
66
|
+
PARTITION BY stream_id
|
|
67
|
+
ORDER BY ts DESC, stream_offset DESC
|
|
68
|
+
) AS recency_rank
|
|
69
|
+
FROM events
|
|
70
|
+
WHERE event_class = 'substantive'
|
|
71
|
+
AND stream_id IN (${a.map(()=>"?").join(", ")})
|
|
72
|
+
)
|
|
73
|
+
WHERE recency_rank = 1`).all(...a).map(wu);if(c.includes(null))return null;i.push(...c)}return Su(i,r)}):null}async function aD(e,t){let n=[...new Set(t.filter(a=>a.trim().length>0&&T.basename(a)===a))];if(n.length===0)return{};let r=new Set(n),o=ao(),i=await lu(o,e,n,r);if(i!==null&&i!==De)return i;if(o&&i!==De&&!await _u(e))try{if(await aE(e,{lockWaitMs:0})){let a=await lu(o,e,n,r);if(a!==null&&a!==De)return a}}catch{}let s=[];return await Promise.all(n.map(async a=>{let c=T.join(e,"history",`${a}.jsonl`);(await iE(c,a).catch(d=>{if(d instanceof y&&d.code==="history_timestamp_invalid")return[];throw d})).forEach((d,l)=>{s.push({stream_id:a,stream_offset:l,entry:d})})})),Su(s,r)}import va from"node:fs/promises";import Wt 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]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();var bE="__pm_suppress_host_output",Rs="@unbrained/pm-cli:suppress-host-output:v1";function ku(e){return e===void 0?{__pm_suppress_host_output:Rs}:{__pm_suppress_host_output:Rs,result:e}}function Cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[bE]===Rs}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="975b7c1d-e398-586a-bd50-b3bf0528d24a")}catch{}})();var co="changed_fields",wE="changed_field_count",xs="rows",vE=new Set(["apply","rollback"]),Ru=new Set(["deleted","would_delete"]),Au=256,Iu={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function EE(e,t){if(!K(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let n=Object.hasOwn(Iu,e.action)?Iu[e.action]:void 0;if(!n||!n.every(i=>{let s=e[i];return K(s)&&K(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let r=e[n.at(-1)],o=xu(r);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(n.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(n.map(i=>[i,Nu(e[i],t)]))}}function Tu(e){return typeof e!="string"||e.length<=Au?e:`${Ie(e,Au-1)}\u2026`}function OE(e){if(!K(e))return null;let t={...e};return t.reason=Tu(t.reason),K(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Tu(r)]))),t}function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Cu(e){let t=e[co];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==co&&(n[r]=o);return n[wE]=t.length,n}function SE(e){return"item"in e&&Array.isArray(e[co])}function kE(e){return typeof e.mode=="string"&&vE.has(e.mode)&&Array.isArray(e[xs])}function AE(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[xs]=t,n}function xu(e){if(!K(e))return null;let t=K(e.item)?e.item:K(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&Ru.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function IE(e,t){if(!K(e))return null;if(K(e.plan)&&K(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!t||!K(e.item)||typeof e.item.id!="string")return null;let n=e[co];if(!Array.isArray(n))return null;let r={id:e.item.id,...typeof e.outcome=="string"&&Ru.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:n.length};return TE(e,e.item,r),r}function TE(e,t,n){let r=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;r!==void 0&&(n.close_reason=r);let o=OE(e.recurrence);o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion","start","takeover"])K(e[i])&&(n[i]=e[i]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(let i of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(e,i)&&(n[i]=e[i])}function RE(e){let t=kE(e)?e[xs]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!K(o))return o;let i=Cu(o);return i?(n=!0,i):o});return n?{projected:AE(e,r),changed:!0}:{projected:e,changed:!1}}function Nu(e,t={}){let n=EE(e,t);if(n!==null)return n;if(t.idOnly===!0){let a=xu(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=IE(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!K(e))return e;let r=!1,o=e,i=SE(e)?Cu(e):null;i!==null&&(o=i,r=!0);let s=RE(o);return s.changed&&(o=s.projected,r=!0),r?o: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]="1f8bc22d-02b9-522a-a2cd-0d34bf6e3ec3")}catch{}})();import{AsyncLocalStorage as KO}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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function $(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function V(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function D(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function Du(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function ot(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function In(e,t){if(ot(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="095ea29d-eda3-5287-b54d-8a961658f7bc")}catch{}})();function Pu(e,t="",n=""){if(e===void 0)return;if(Lt(t)||Lt(n))throw new TypeError("Native pm commands and actions cannot declare read_output");let r=$("registerCommand definition.read_output",e);if(Object.keys(r).some(s=>s!=="row_keys")||!Array.isArray(r.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(r.row_keys),i=new Set(["__proto__","constructor","prototype","row_contract","read_output","read_session","omission_receipt","output_budget_truncation"]);if(o.some(s=>typeof s!="string"||!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*$/u.test(s)||s.split(".").some(a=>i.has(a))))throw new TypeError("registerCommand definition.read_output row_keys must be safe dot-delimited property paths");if(new Set(o).size!==o.length||o.some(s=>o.some(a=>a.startsWith(`${s}.`))))throw new TypeError("registerCommand definition.read_output row_keys must be unique and non-overlapping");return Object.freeze({row_keys:Object.freeze([...o])})}function Lt(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return It.includes(t)||Ke.includes(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]="a65d6520-0e6f-5627-a4dd-bd455c2db0fa")}catch{}})();var ju=new WeakMap;function wD(e,t){ju.set(e,new Set(t))}var lo='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',CE={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},xE=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function vD(e,t,n){if(e&&t)throw new y(`${n} cannot be combined with --full`,g.USAGE)}function de(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function ED(e,t){let n=xE.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return de([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return de(r)}var NE=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var DE=new Set([void 0,"tabular_when_uniform"]),PE=new Set(["collection","none"]),$E=new Set(["supported","unsupported"]);function $u(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function ME(e){return q(e)&&typeof e.command=="string"&&e.command.trim().length>0&&PE.has(e.row_kind)&&$u(e.row_keys,!0)&&(e.continuation_row_keys===void 0||$u(e.continuation_row_keys,!1))&&$E.has(e.fields)&&DE.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var jE={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},LE={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function FE(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=jE[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||q(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:lo}:{},toon_encoding:"tabular_when_uniform"}}let o=CE[r],i=LE[r];return o===void 0||i===void 0||!i.some(s=>Object.hasOwn(t,s))?void 0:(()=>{let s=o.row_keys.filter(a=>{let c=a.split(".").reduce((d,l)=>q(d)?d[l]:void 0,t);return Array.isArray(c)||q(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:lo}:{},toon_encoding:"tabular_when_uniform"}})()}function UE(e){if(!q(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>q(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return de(r,new Set(o))}function zE(e){if(!Array.isArray(e.sections_included))return;let t=de(NE,new Set(e.sections_included.filter(n=>typeof n=="string")));return q(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function HE(e,t,n){if(e==="dependency_provenance")return!1;let r=Lu(e);if(r!==void 0){let o=n[r.facet];return q(o)&&Object.hasOwn(o,r.member)}return Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&q(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&q(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function Lu(e){let t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function BE(e){if(!q(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=ju.get(e),i=a=>n.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...n,...r.slice(1),...o?.has("dependency_provenance")?["dependency_provenance"]:[],...o?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[],...[...o??[]].filter(a=>Lu(a)!==void 0)].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:a==="blockers"?"--full":a==="dependency_provenance"?"--fields dependencies":`--fields ${a}`}));return de(s,new Set(s.flatMap(({name:a})=>HE(a,i(a),e)?[a]:[])))}function Mu(e){if(q(e.projection))return de([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function VE(e){if(!q(e.projection))return de([]);if(typeof e.projection.mode=="string")return de([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function qE(e){if(!(!q(e.selected)||typeof e.selected.summary!="boolean"))return de([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function WE(e,t){let n=UE(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return zE(t);if(r==="get")return BE(t);if(r==="list"||r.startsWith("list-"))return Mu(t);if(r==="search")return Mu(t)??de([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return VE(t);if(r==="contracts")return qE(t)}function Fu(e,t){if(e===void 0||!q(t))return t;let n=WE(e,t),r=t.row_contract,o=ME(r)?r:FE(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return q(i.omission_receipt)||n===void 0?i:{...i,omission_receipt: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]="e1fd9abd-a586-5302-940e-eec2a3eb8641")}catch{}})();function Ns(e){let t=e.trim().toLowerCase().startsWith("extension:"),n=e.trim().toLowerCase().replace(/^extension:/u,"");if(Lt(n))return;let r=Uu()?.commands??[],o=[...r].reverse().find(s=>s.command===n)?.command??(t?void 0:r.find(s=>s.action===n)?.command),i=[...r].reverse().find(s=>s.command===o);return i===void 0||Lt(i.command)||Lt(i.action)?void 0:i}function GE(e){let t=Ns(e);return t?.read_output===void 0?void 0:t}function KE(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Read-only extension commands must return a structured object.",g.USAGE,{code:"extension_read_output_invalid"});for(let n of e.row_keys){let r=t;for(let o of n.split("."))r=typeof r=="object"&&r!==null&&Object.hasOwn(r,o)?Reflect.get(r,o):void 0;if(r===null||typeof r!="object")throw new y(`Read-only extension result is missing declared row collection ${n}.`,g.USAGE,{code:"extension_read_output_invalid",required:`Return ${n} as an object or array (an empty collection is valid); an output_format service renders the compact receipt from it.`,why:"A command that declares read_output.row_keys promises those row collections, and pm checks them before projection, budgeting or custom formatting."})}}function zu(e,t){let n=GE(e),r=n?.read_output;return r===void 0?t:(KE(r,t),{...t,row_contract:{command:`extension:${n.command}`,row_kind:r.row_keys.length>0?"collection":"none",row_keys:[...r.row_keys],fields:"supported",...r.row_keys.length>0?{jq_selector:lo}:{},toon_encoding:"tabular_when_uniform"}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9bb3b2ed-c289-5b96-99ce-9df6e202c464")}catch{}})();var Hu=new Set(["--pm-path","--path","--author","--expect-hash","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),YE=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function XE(e){let t=e.indexOf("=");return t>0&&Hu.has(e.slice(0,t))}function JE(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function Bu(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")return;if(Hu.has(n)){t+=JE(n,e[t+1])?1:0;continue}if(!(XE(n)||YE.has(n)||n==="--profile"||n==="--id-only"||n==="--explain")&&!n.startsWith("-"))return t}}function CD(e){let t=Bu(e);return t===void 0?void 0:e[t].trim().toLowerCase()}import QE from"node:path";import Vu from"path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();function Tn(e,t){let n=Vu.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!Vu.isAbsolute(n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f08c44a-dfdf-5c23-8f68-0e3ed73582b0")}catch{}})();var Ds=new WeakMap;function HD(e){Ds.set(e,e.path)}function ZE(e){if(!process.env.PM_PATH?.trim())return;let t=hr(e);return Tn(nd(t),e)&&t===fi(e)?void 0:QE.relative(e,t)||"."}function BD(e,t=process.cwd()){let n=Ds.has(e)?Ds.get(e):e.path,r=n?.trim()?n:ZE(t),o=r?["--pm-path",r]:[];return e.noExtensions&&o.push("--no-extensions"),o}import{createHash as RO}from"node:crypto";import{createHash as vO}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]="040fff2e-c66f-5091-9ea8-7dcdaf6e203b")}catch{}})();var Ps={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"],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","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},learnings:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},$s=new Set(["--collapse","--fields","--section"]),uo=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 --output-budget 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 fo(e){return e.slice(2).replaceAll("-","_")}function qu(e,t={}){let n=e==="package catalog"||e==="packages catalog"||e==="package-catalog"||(e==="package"||e==="packages"||e==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":e==="package manage"||e==="package-manage"?"package-manage":e.split(" ")[0],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return Ke.includes(r)?r:void 0}function Ms(e){return new Map((Ps[e]?.include??[]).filter(t=>!$s.has(t)&&uo[t]===void 0).map(t=>[fo(t),js(t)]))}function js(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f539ecb5-2f49-5867-96c7-48eddb81a628")}catch{}})();var e0=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function U(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Wu(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!U(n))return;n=n[r]}return n}function Ls(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[s];if(Array.isArray(i)){let d=Number(a),l=[...i];return l[d]=o(i[d],s+1),l}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function Fs(e,t,n,r){let o=ge(e).find(a=>a.path===t);if(!o)return e;let i=Array.isArray(o.value)?o.value.slice(n,r):Object.fromEntries(Object.entries(o.value).slice(n,r)),s=Ls(e,t,i);return U(s.summary)&&U(s.summary.focus_row_states)&&typeof s.summary.focus_row_states[t]=="string"&&(s.summary={...s.summary,focus_row_states:{...s.summary.focus_row_states,[t]:s.summary.focus_row_states[t].slice(n,r)}}),xn(s),s}function po(e){let t=e.row_contract;return U(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function t0(e){let t=e.row_contract;return U(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):po(e)}function Pe(e){return po(e).flatMap(t=>{let n=Wu(e,t);return Array.isArray(n)||U(n)?[{path:t,value:n}]:[]})}function ge(e){return t0(e).flatMap(t=>{let n=Wu(e,t);return Array.isArray(n)||U(n)?[{path:t,value:n}]:[]})}function Rn(e){let t=Pe(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(U(o))for(let[s,a]of Object.entries(o))i.length===0&&e0.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function Ft(e){return Pe(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function Cn(e,t){let n=e;for(let r of Pe(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=Ls(n,r.path,o)}return n}function Gu(e,t,n=()=>!1){let r=e,o=!1;for(let i of Pe(r)){let s=Array.isArray(i.value)?i.value:Object.entries(i.value);if(s.length<=t)continue;o=!0;let a=n(i.path)?s.length-t:0,c=s.slice(a,a+t),d=Array.isArray(i.value)?c:Object.fromEntries(c);r=Ls(r,i.path,d)}return{result:r,truncated:o}}var Ku=["high_level","low_level","blocked_fallback"];function mo(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function GD(e,t){if(!U(e.summary)||!U(e.summary.returned_focus))return;let n=new Map(t.map(r=>[r.id,r]));e.summary={...e.summary,focus_row_states:Object.fromEntries(Ku.map(r=>[r,Array.isArray(e[r])?e[r].filter(U).map(o=>mo(n.get(o.id)??o)).join(""):""]))}}function n0(e,t){if(e!==void 0){if(typeof e!="string"||e.length!==t||!/^[iIoO]*$/u.test(e))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return e}}function r0(e,t,n,r){let o=Array.isArray(t[n])?t[n].filter(U):[],i=n0(r[n],o.length)??o.map(mo).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[n])?e[n].filter(U):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??mo(d);return u!==mo(d)&&(c=!0),u}).join(""),needsStates:c}}function o0(e,t){typeof e.count=="number"&&(e.count_only===!0||t.count_only===!0?typeof t.count=="number"&&(e.count=t.count):Array.isArray(e.items)&&(e.count=e.items.length))}function xn(e,t=e){if(o0(e,t),!U(e.summary)||!U(e.summary.returned_focus))return;let n={...e.summary},r=U(t.summary)&&U(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=Ku.map(c=>({key:c,...r0(e,t,c,r)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof n.high_level=="number"&&(n.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof n.low_level=="number"&&(n.low_level=Array.isArray(e.low_level)?e.low_level.length:0),n.returned_focus={active_items:a.length,in_progress:[...a].filter(c=>c.toLowerCase()==="i").length,open:[...a].filter(c=>c.toLowerCase()==="o").length,blocked:[...a].filter(c=>c===c.toUpperCase()).length},s?n.focus_row_states=i:delete n.focus_row_states,e.summary=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]="42dab49d-bb4e-558c-9cc1-3f50ac354f3b")}catch{}})();var Bs=8,i0=64,s0=5,a0=4,Yu=100,Qu=new WeakMap,Zu=new WeakMap;function ef(e,t){Qu.set(e,t)}function Vs(e){return Qu.get(e)}function tf(e,t){Zu.set(e,t)}function nf(e,t,n){if(e!=="get"||!Us(n.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(c=>t[c]!==void 0)||t.full===!0||t.tree===!0||t.depth!==void 0&&t.depth!=="standard")return;let r=n.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(n,c)),s=Object.fromEntries(Object.entries(n).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(r).filter(([c])=>c!=="body")),Object.hasOwn(r,"body")&&i.push("body");let a=[...Us(n.omission_receipt)&&Array.isArray(n.omission_receipt.omitted_field_groups)?n.omission_receipt.omitted_field_groups:[],...i.map(c=>({name:c,restore_with:`--fields ${c}`}))];return s.omission_receipt={has_omissions:a.length>0,omitted_field_group_count:a.length,omitted_field_groups:a},s}function Dn(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*s0/a0),i=Math.ceil(o/Yu)*Yu;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function Ut(e,t,n=!1){let r=Object.getOwnPropertyDescriptor(e,"row_contract");r&&(n||r.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...r,enumerable:!1})}function it(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}var Nn;function ye(e,t){let n=t===void 0?JSON.stringify(e):Nn!==void 0&&Nn.format===t?c0(Nn,e):Ju(e,t);return Math.ceil(Buffer.byteLength(n,"utf8")/4)}function c0(e,t){Nn=void 0;try{return e.render(t)}finally{Nn=e}}function Us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zs(e,t,n=!1,r=!0){return typeof e=="string"?n?e:(e.length>dn&&(t.compacted=!0),Ar(e)):Array.isArray(e)?e.map(o=>zs(o,t,n,r)):Us(e)?Object.fromEntries(Object.entries(e).map(([o,i])=>[o,zs(i,t,n||r&&(o==="focus_row_states"||typeof i=="string"&&ln(o)),r)])):e}function $e(e,t,n){let r=t.estimated_tokens;for(let o=0;o<Bs;o+=1){Hs(e,t,r);let i=ye(e,n);if(i===r)return!0;r=i}return Hs(e,t,r),!1}function Hs(e,t,n){t.estimated_tokens=n,Zu.get(t)?.(e,n)}var d0=4;function Xu(e,t,n,r){$e(e,t,r);let o=t.estimated_tokens;o<=n||o-10**(String(o).length-1)>=d0||(t.estimated_tokens=0,!($e(e,t,r)&&t.estimated_tokens<=n)&&Hs(e,t,o))}function l0(e,t){return Rn(e).filter(n=>(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length)>Math.max(1,t.get(n.path)??0)).map(n=>({collection:n,length:Array.isArray(n.value)?n.value.length:Object.keys(n.value).length})).sort((n,r)=>r.length-n.length||n.collection.path.localeCompare(r.collection.path))[0]?.collection}function u0(e,t,n,r,o,i,s){for(let a=0;a<i0;a+=1){if(i?.(e),Xu(e,t,n,o),t.estimated_tokens<=n)return;let c=l0(e,r);if(!c)return;let d=Math.max(1,r.get(c.path)??0),l=Array.isArray(c.value)?[...c.value]:Object.entries(c.value),u=s(c.path),f=_=>{let b=u?l.length-_:0;if(Array.isArray(c.value)){c.value.length=_;for(let E=0;E<_;E+=1)c.value[E]=l[b+E]}else{for(let E of Object.keys(c.value))delete c.value[E];Object.defineProperties(c.value,Object.getOwnPropertyDescriptors(Object.fromEntries(l.slice(b,b+_))))}typeof e.count=="number"&&(e.count=Ft(e)),typeof e.returned_count=="number"&&(e.returned_count=Ft(e)),c.path==="items"&&(e.applied_limit=_),i?.(e),Xu(e,t,n,o)};t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],c.path])].sort((_,b)=>_.localeCompare(b)),e.has_more=!0,e.truncated=!0;let m=d,p=l.length-1,h=d;for(;m<=p;){let _=Math.floor((m+p)/2);f(_),t.estimated_tokens<=n?(h=_,m=_+1):p=_-1}f(h)}}function rf(e,t,n,r=new Map,o,i,s=!1,a=()=>!1,c){let d={compacted:!1},l=Object.fromEntries(Object.entries(e).map(([u,f])=>[u,zs(f,d,s&&u==="diff"||typeof f=="string"&&ln(u),!Ir(c,u))]));return Ut(e,l),t.strings_compacted=d.compacted,l.read_output=t,u0(l,t,n,r,o,i,a),$e(l,t,o),l}import{stripVTControlCharacters as f0}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]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();var m0=["full","compact","brief","summary","counts"],rP=["mutation","read","discovery","governance"],sf=["error","warning","validation_summary","recovery_bundle"],p0=["full","omit_explanation","limit_collections","compact_recovery","action_only"],_0=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"]),h0=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),g0=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),y0={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},b0=3,w0=2,v0=192,E0={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},O0=sf.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:E0[e],minimum_max_estimated_tokens:v0,degradation_ladder:p0,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),S0=new Map(O0.map(e=>[e.diagnostic_class,e]));function k0(e){let[t=""]=cn(e).split(/\s+/u);return _0.has(t)?"mutation":h0.has(t)?"discovery":g0.has(t)?"governance":"read"}function af(e,t=k0(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=y0[t];return A0({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*b0/w0)},degradation_ladder:m0,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function A0(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 I0=wr.map(e=>af(e)),T0=new Map(I0.map(e=>[e.command,e]));function cf(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=cn(n).split(" "),o=T0.get(r);return o?{...o,command:n}:t.generateFallback?af(n):null}function at(e){return Math.ceil(Math.max(0,e)/4)}function df(e){let t=S0.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${sf.join(", ")}`);return t}function Me(e){return at(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function R0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qs(e){if(!R0(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function C0(e,t){return typeof e!="string"||e.length<=t?e:`${Ie(e,Math.max(1,t-3))}...`}function st(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function lf(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var x0=new Set(["limit_collections","compact_recovery","action_only"]),N0=new Set(["compact_recovery","action_only"]);function D0(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:C0(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=qs(e.recovery);return n!==void 0?t.recovery=n:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function P0(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),x0.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(N0.has(t)){let r=qs(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?lf(n):D0(n)}function zt(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=Me(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function $0(e,t,n){let r=zt(e,t);for(let i of["recovery","exit_code"])Me(r)<=n||e[i]===void 0||(delete e[i],r=zt(e,t));let o=40;for(;Me(r)>n&&o>4;)o-=4,e.code=st(String(e.code),o),e.required=st(String(e.required),o),r=zt(e,t);return r}function M0(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>st(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=qs(e.recovery),c=a&&Me(a)<=48?a:void 0,d={code:st(String(e.code),320),required:st(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=zt(d,s);for(;Me(l)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,l=zt(d,s);return l=$0(d,s,t),l}function oP(e,t={}){let n=e,r=t.diagnosticClass??"error",o=df(r),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=Me(n),c=Object.keys(n);if(a<=s)return lf(structuredClone(n));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=P0(n,u),m=c.filter(h=>!Object.hasOwn(f,h)),p=zt(f,{diagnostic_class:r,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:l>0,degradation_steps:o.degradation_ladder.slice(0,l+1),omitted_fields:m});if(d=p,Me(p)<=s)break}return Me(d)>s&&(d=M0(d,s)),d}function of(e){return f0(e).replace(/\r\n/gu,`
|
|
74
|
+
`).replace(/[^\P{Cc}\n]/gu," ")}function iP(e,t,n={}){let r=n.diagnosticClass??"error",o=df(r),i=n.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=of(e),c=at(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
|
|
75
|
+
`,u=`
|
|
76
|
+
|
|
77
|
+
${st(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
|
|
78
|
+
|
|
79
|
+
Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=of(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),p=d?`${l}${st(f,m)}${u}`:a;return{output:p,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:at(Buffer.byteLength(p,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}var Ws=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function sP(e){return e?.trim()===Ws.required}function aP(e){let t=e?.trim();return t!==void 0&&Ws.why.includes(t)}function cP(e){return(e??[]).filter(t=>!Ws.examples.includes(t.trim()))}var dP=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function lP(e){if(!e)return;let{attempted_command:t,normalized_args:n,provided_fields:r,...o}=e;return Object.values(o).some(i=>i!==void 0)?o: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]="3a351971-6cfb-55eb-a266-3fec0af9eaa4")}catch{}})();var ee=Object.freeze({comments:Object.freeze({paths:Object.freeze(["comments"]),total_key:"total_count"}),notes:Object.freeze({paths:Object.freeze(["notes"]),total_key:"total_count",delivered_row_counters:Object.freeze([Object.freeze({key:"structured_event_count",field:"format",equals:"json"})])}),learnings:Object.freeze({paths:Object.freeze(["learnings"]),total_key:"total_count"})});function be(e,t){return e===void 0?!1:(Object.hasOwn(ee,e)?ee[e]:void 0)?.paths.includes(t)===!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]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function gP(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var Gs=256,Ks=1e4,j0=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,uf=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,L0=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),F0=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&j0.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Gs,reason:`token_budget must be a safe integer of at least ${Gs}.`},{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<=Ks&&e.seen_item_ids.every(t=>typeof t=="string"&&uf.test(t)),reason:`seen_item_ids must contain at most ${Ks} portable item identifiers.`}];function ho(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _o(e){throw new y(`--output-session ${e}`,g.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function go(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{_o("must be a valid JSON object.")}ho(t)||_o("must be a JSON object.");let n=Object.keys(t).filter(i=>!L0.has(i));n.length>0&&_o(`contains unknown field "${n.sort()[0]}".`);let r=F0.find(i=>!i.valid(t));r!==void 0&&_o(r.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function ff(e){if(ho(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:ho(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function U0(e){let t=new Set,n=0,r=Pe(e),o=new Set(r.map(({path:s})=>s)),i=Object.entries(e).flatMap(([s,a])=>Array.isArray(a)&&!o.has(s)?[{path:s,value:a}]:[]);for(let s of[...r,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!ho(c))continue;if(typeof c.context_ref=="string"){n+=1;continue}let d=ff(c);d!==void 0&&uf.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:n}}function mf(e,t){let n=new Set(t.seen_item_ids);return Cn(e,r=>{let o=ff(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function Ys(e,t,n){let{deliveredIds:r,suppressedRepeatCount:o}=U0(e),i=new Set(t.seen_item_ids),s=[...r].filter(h=>!i.has(h)).sort(),a=s.slice(0,Ks-t.seen_item_ids.length),c=[...t.seen_item_ids,...a].sort(),d=s.length-a.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:r.size,...d===0?{}:{seen_item_overflow_count:d},suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --depth brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:c}},u={...e,read_session:l},f=h=>{l.spent_this_call_tokens=h,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,h),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<Gs,l.next_state.spent_tokens=l.spent_total_tokens},m=0,p=0;for(let h=0;h<8;h+=1){f(m);let _=ye(u,n);if(_===m)return u;p=Math.max(p,_),m=_}return f(p),u}function pf(e){return Math.max(0,e.token_budget-e.spent_tokens)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cc0fcb7-2aaa-5233-bdfd-4b4d0fb3e9c1")}catch{}})();var Pn=Symbol.for("pm.readOutputInvocationProvenance");function bP(e,t){return Reflect.set(e,Pn,{canonical_include_modes:[...t],explicit_legacy_aliases:[],sdk_invocation_observed:!0}),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]="0456278a-5928-5a60-8d53-d12ffb1a7a5d")}catch{}})();var ct=["include","amount","cost","encoding"],Ef=["canonical","legacy","intent","default"],Mn=vr,FP=Object.freeze(ct.map(e=>Mn[e])),UP=Er;function z0(e,t){let n=uo[e];if(n!==void 0)return n;let r=t==="include"?$s.has(e)?"<csv>":fo(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Mn[t]} ${r}.`}function Of(e){let t=Ps[e]??{},n=Object.freeze(Object.fromEntries(ct.map(r=>[r,Object.freeze({dimension:r,canonical_option:Mn[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:uo[o]===void 0?"replacement":"behavior_preserving",migration_hint:z0(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Ef,budget_retention_policy:e==="assurance"?"verdict_priority":Object.hasOwn(ee,e)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...Ms(e).keys()])})}var H0=Object.freeze(Ke.map(Of)),B0=new Map(H0.map(e=>[e.command,e]));function we(e,t={}){let n=cn(e.trim().toLowerCase()),r=Ns(n);return r!==void 0?r.read_output===void 0?void 0:`extension:${r.command}`:qu(n,t)}var V0=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],_f={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function q0(e){return V0.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var W0=[{keys:["outputInclude","output_include"],valid:e=>$n(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||Ht(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||Ht(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(go(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],zP="read_output_mutation_conflict",Sf=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],HP=Sf.map(({flag:e})=>e);function G0(e,t,n){let r=Sf.filter(({keys:a})=>a.some(c=>t[c]!==void 0)),o=r.map(({flag:a})=>a),i=r.flatMap(({keys:a})=>a.filter(c=>t[c]!==void 0)),s=o.join(", ");return new y(`Universal output controls (${s}) cannot be combined with a ${e} mutation; nothing was written.`,g.USAGE,{code:"read_output_mutation_conflict",field:o[0],details:{surface:e,output_controls:o,output_option_keys:i,mutation_options:[...n]},required:`Retry the ${e} mutation without ${s}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...K0[e]]})}var K0={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]};function BP(e,t){let n=t.outputFormat??t.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new y("--output-format must be toon or json.",g.USAGE);if(!q0(t))return;let r=we(e,t);if(!r)throw new y(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,g.USAGE);if(Object.hasOwn(_f,r)){let o=r,i=_f[o].filter(s=>t[s]!==void 0&&t[s]!==!1);if(i.length>0)throw G0(o,t,i)}for(let o of W0){let i=o.keys.map(s=>t[s]).find(s=>s!==void 0);if(i!==void 0&&!o.valid(i))throw new y(o.message,g.USAGE)}}function kf(e){let t=we(e);return t?Ms(t):new Map}function Y0(e,t,n){let r=$n(t)??[],o=kf(e),i=[],s=[],a=n,c=a[Pn],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of r){let p=o.get(m);if(p===void 0){i.push(m);continue}let h=`--${m.replaceAll("_","-")}`;Js(Xs(n,h))&&l.add(h),n[p]=!0,s.push(m),d.add(m)}let u=we(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...$n(n.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[Pn]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function VP(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=Y0(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function Xs(e,t){let n=js(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function Js(e){return e!==void 0&&e!==!1&&e!==null}function $n(e){let t=(Array.isArray(e)?e:[e]).flatMap(n=>typeof n=="string"?n.split(","):[]).map(n=>n.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function Ht(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function X0(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=Xs(t,o.flag),s={value:i,flag:o.flag};if(Js(i)&&n(s))return s}}function hf(e,t){let n=$n(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:$n(t.value)??[fo(t.flag)]}}function gf(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Ht(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=Ht(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function yf(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Ht(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=Ht(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function bf(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function Af(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function J0(e,t,n,r){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||Js(Xs(r,"--no-truncate"))&&!Af(n,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function Q0(e,t){return ct.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[Mn[n]]:[])}function If(e,t){let n=we(e,t);if(!n)return;let r=B0.get(n)??Of(n),o=t[Pn],i={include:b=>hf(void 0,b),amount:b=>gf(void 0,b),cost:b=>yf(void 0,b),encoding:b=>bf(void 0,b)},s=Object.fromEntries(ct.map(b=>[b,X0(r.dimensions[b],t,E=>i[b](E)!==void 0,E=>Af(o,b,E))])),a=ct.flatMap(b=>{let E=s[b];return E?[E.flag]:[]}),c=ct.flatMap(b=>{let E=s[b];return E?[r.dimensions[b].legacy_aliases.find(j=>j.flag===E.flag).migration_hint]:[]}),d=bf(t.outputFormat??t.output_format,s.encoding),l=hf(t.outputInclude??t.output_include,s.include),u=gf(t.outputLimit??t.output_limit,s.amount),f=yf(t.outputBudget??t.output_budget,s.cost),m=J0(e,s,o,t),p=cf(e,{generateFallback:!0}),h=d?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",_=f??(m?{source:"intent",value:"unbounded"}:{source:"default",value:p.default_max_estimated_tokens_by_format[h]});return{command:n,include:l,amount:u,cost:_,encoding:d,canonical_options_used:Q0({include:l,amount:u,cost:_,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:Ef}}function M(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Qs=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),Z0=["collection_counts","notes_count","tests_count"];function Tf(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function eO(e){let t=M(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...Z0.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Qs.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function tO(e,t){let n=eO(e),r=t.filter(l=>!n.valid.includes(l));if(r.length>0)throw new y(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,g.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:n.itemFields.includes(l)?[l]:[]).filter((l,u,f)=>f.indexOf(l)===u);if(o&&i.length>0)throw new y("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",g.USAGE);let s=new Set(t.filter(l=>n.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>Qs.has(l)||s.has(l)));o?a.item=n.item:i.length>0&&(a.item=Tf(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...M(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function wf(e){let t=0;return Cn({...e},n=>(M(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function nO(e,t,n,r){if(wf(t)===0||wf(n)>0)return;let o=[...kf(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new y(`Unknown --output-include selector(s) for ${e}: ${r.join(", ")}. No selector matched any returned row field.${i}`,g.USAGE)}function rO(e,t,n){if(e==="get")return tO(t,n);let r=po(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=Cn(s,d=>M(d)?Tf(d,a):d);return nO(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||Qs.has(s)))}function oO(e,t,n,r){if(t==="unbounded")return e;let{result:o,truncated:i}=Gu(e,t,s=>be(n,s));if(!i)return o;if(o.has_more=!0,o.truncated=!0,Pf(o,n,[...r.entries()].flatMap(([s,a])=>a.rows>t?[{path:s,total_rows:a.totalRows}]:[])),typeof o.count=="number"){let s=M(o.projection)?o.projection.row_key:void 0;o.count=typeof s=="string"&&Array.isArray(o[s])?o[s].length:Ft(o)}return typeof o.returned_count=="number"&&(o.returned_count=Ft(o)),o.applied_bound={kind:"output_limit",source:"explicit",value:t},o}function iO(e){return ct.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(Mn[t]))}function yo(e,t,n,r){let o=Ys(e,t,r);Ut(e,o);for(let i=0;i<8;i+=1){let s=n.estimated_tokens,a=o.read_session.spent_this_call_tokens;$e(o,n,r);let c=o;o=Ys(o,t,r),Ut(c,o);let d=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===s&&d===a)return o}return o}function Zs(e,t){if(!M(e.read_output))return e;let n=it(t),r=e.read_output,o=go(t.outputSession??t.output_session);return o===void 0?($e(e,r,n),e):yo(e,o,r,n)}function Rf(e,t){if(e!=="validate")return t;let n=M(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(l=>M(l)&&l.name==="diagnostic_rows"))return t;let r=[...new Set(Rn(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=r.filter(l=>!r.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=M(t.row_contract)?t.row_contract:{},s=Array.isArray(i.row_keys)?i.row_keys.filter(l=>typeof l=="string"):[],a=Array.isArray(i.continuation_row_keys)?i.continuation_row_keys.filter(l=>typeof l=="string"):[],c=s.length>0?s:o,d=[...new Set(o)];return JSON.stringify(c)===JSON.stringify(s)&&JSON.stringify(d)===JSON.stringify(a)?t:{...t,row_contract:{...i,row_keys:c,continuation_row_keys:d,jq_selector:typeof i.jq_selector=="string"?i.jq_selector:".checks[].details"}}}function sO(e,t){return e.include?.source==="canonical"&&!dt(t)}function Cf(e,t){let n={...e};return sO(t,e)&&(n=rO(t.command,n,t.include.value)),t.command==="assurance"?Uf(n):n}function aO(e,t){let n=Vs(t)?.continuationBinding;if(n===void 0)return;let r=Cf(Rf(e.command,n),e);return new Map(ge(r).filter(o=>!be(e.command,o.path)).map(o=>[o.path,o]))}function cO(e,t,n,r,o){let i=Cf(e,t);xn(i,e);let s=aO(t,o);if(i=zf(i,t.command,r,s),t.command==="history"&&r){let d=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([l])=>!d.includes(l)||l===r.path)),M(i.projection)&&(i.projection={...i.projection,row_key:r.path}),M(i.row_contract)){let l=i.row_contract;i.row_contract={...l,row_keys:[r.path],...Array.isArray(l.continuation_row_keys)?{continuation_row_keys:[r.path]}:{}}}i.count=Object.keys(i[r.path]).length}let a=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,c=hO(i,e,t.command,r,o,s);return t.amount?.source==="canonical"&&(i=oO(i,t.amount.value,t.command,c.collectionsBeforeBudget),c.cursorContinuesExistingPage&&Mf(i,c.originalItems,c.cursorSource,!0,c.originalItemOffset)),xn(i,a),$f(i,t.command,c),{projected:n===void 0?i:mf(i,n),continuationState:c}}function dO(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default"||e.command==="context"&&e.cost.source==="legacy")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:pf(t)}]].sort((n,r)=>n.tokens-r.tokens)[0]}function xf(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function Nf(e,t){return M(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function lO(e,t,n){return e.command!=="next"||(t.tokenBudget??t.token_budget)===void 0?!1:!(M(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function Df(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!Nf(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function uO(e,t,n,r,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...Df(r),precedence:e.precedence,...xf(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:o}:{}},a={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:s},c=n===void 0?a:yo(a,n,s,i);if(n===void 0&&$e(c,s,i),n!==void 0&&s.estimated_tokens>r.tokens)throw new y("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",g.USAGE);return c}function fO(e,t,n){return e.command==="context"&&e.cost?.source==="legacy"&&!Nf(n,e.cost.value)||lO(e,t,n)||t.outputRowContract===!0||t.output_row_contract===!0||e.canonical_options_used.includes("--output-include")||e.command==="list"&&e.canonical_options_used.length>0&&e.include?.value.includes("full")===!0}function mO(e,t,n,r,o){if(t!==void 0||dt(n)||fO(e,o,n))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(Pe(n).some(({value:s})=>(Array.isArray(s)?s.length:Object.keys(s).length)>i))return!1}return e.cost===void 0||e.cost.value==="unbounded"||e.cost.source==="legacy"&&e.command!=="context"||ye(o.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,r)<=e.cost.value}function Pf(e,t,n){let r=Object.hasOwn(ee,t)?ee[t]:void 0,o=n.find(i=>r?.paths.includes(i.path));r!==void 0&&o!==void 0&&typeof e[r.total_key]!="number"&&(e[r.total_key]=o.total_rows)}function $f(e,t,n){let r=ee[t]?.paths[0];r!==void 0&&Ff(e,t,n.producer,n.collectionsBeforeBudget.get(r)?.rows)}function pO(e,t,n,r){let o=n.backward?n.rows-r:n.baseOffset+r;return{path:t,cursor:ea({command:e,path:t,offset:o,total_rows:n.totalRows,fingerprint:n.fingerprint,...n.backward?{direction:"backward"}:{}}),retained_rows:r,remaining_rows:n.backward?o:n.totalRows-o,total_rows:n.totalRows}}function _O(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(ge(e).map(p=>[p.path,Array.isArray(p.value)?p.value.length:Object.keys(p.value).length])),d=[...s.entries()].flatMap(([p,h])=>{let _=c.get(p);return _>=h.rows?[]:[pO(t.command,p,h,_)]}),l=d[0];Pf(e,t.command,d);let u=l?"; page --output-cursor":"",f=r.source==="session"?`Truncated by the remaining ${r.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${r.tokens}-token: raise --output-budget${u}`;n.migration_hints=[f,...t.migration_hints];let m=Dn({effective_budget_tokens:r.tokens,measured_result_tokens:i});l&&!o&&(typeof e.next_cursor!="string"||e.continuation_kind==="output_cursor")&&(e.next_cursor=l.cursor),e.continuation_kind=o?"producer_cursor":l?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:d.length>0,recovery_budget_multiplier:l?1:m.recovery_budget_multiplier,continuations:d,restore_with:l?"recovery":`Retry with --output-budget ${m.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${m.output_budget}`,sdk:{outputBudget:m.output_budget},mcp:{outputBudget:m.output_budget}}}}function Mf(e,t,n,r,o){if(typeof n!="string"||!Array.isArray(e.items))return!1;let i=e.items.length,s=t.length;if(i===0||i>=s)return!1;let a;try{a=ta(n)}catch{return!1}let c=a.after_index;if(c===void 0)return!1;let d=t[i-1];if(Object.prototype.toString.call(d)!=="[object Object]")return!1;let l=Reflect.get(d,"id");if(typeof l!="string"||l.length===0)return!1;let u=r?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=jn(a.fingerprint,l,u,a.snapshot),!0)}function vf(e){return Array.isArray(e)?e.length:Object.keys(e).length}function hO(e,t,n,r,o,i){let s=new Map(ge(e).map(d=>{let l=vf(d.value),u=r?.path===d.path,f=be(n,d.path),m=i?.get(d.path)??d,p;return[d.path,{rows:l,totalRows:u?r.total_rows:vf(m.value),baseOffset:u&&!f?r.offset:0,backward:f,get fingerprint(){return p??=u?r.fingerprint:bo(d.path,m.value,n),p}}]})),a=typeof e.next_cursor=="string",c=r?.path==="items"?r.offset:0;return{collectionsBeforeBudget:s,originalItems:Array.isArray(t.items)?c>0?t.items.slice(c):t.items:[],originalItemOffset:c,cursorContinuesExistingPage:a,cursorSource:a?e.next_cursor:o.after,producer:t}}function gO(e,t,n,r,o,i,s,a,c,d){let l={...t,count_only:n},u=r.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>M(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),r.command==="history"&&Array.isArray(e.diff))for(let m of Rn(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return rf(e,o,i.tokens,f,d,m=>{xn(m,l),$f(m,r.command,a);let p=Mf(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(_O(m,r,o,i,p,c,a.collectionsBeforeBudget),r.command==="history"&&M(m.projection)){m.has_more=typeof m.next_cursor=="string"||m.applied_bound?.kind==="output_limit";let h=m.projection.row_key;typeof h=="string"&&Array.isArray(m[h])&&(m.count=m[h].length)}s!==void 0&&Object.assign(m,yo(m,s,o,d))},r.command==="history"&&Array.isArray(e.diff),m=>be(r.command,m),r.command)}function jf(e,t,n){let r=If(e,t);if(!r)return n;let o=it(t),i=go(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?lt(s):void 0,c=iO(r),d=Rf(r.command,n);if(a===void 0&&mO(r,i,d,o,t))return d;let l=dO(r,i),u=cO(d,r,i,a,t),f=u.projected;Ut(f,f,t.outputRowContract===!1);let m=dt(f),p={contract_version:1,command:r.command,requested_dimensions:c,...Df(l,f),precedence:r.precedence,...xf(r),legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.migration_hints,estimated_tokens:0,within_budget:!m,strings_compacted:!1,rows_compacted:!1,result_omitted:m};f.read_output=p;let h=Vs(t)?.mirrorEstimate;if(h!==void 0&&tf(p,h),f=i===void 0?f:yo(f,i,p,o),$e(f,p,o),l!==void 0&&p.estimated_tokens>l.tokens){let _=nf(r.command,t,f);_!==void 0&&(p.applied_depth="brief",p.degradation_reason="output_budget_reached",Ut(f,_),f=Zs(_,t)),p.estimated_tokens>l.tokens&&(f=gO(f,f,d.count_only===!0,r,p,l,i,u.continuationState,p.estimated_tokens,o))}return l!==void 0&&p.estimated_tokens>l.tokens?uO(r,c,i,l,p.estimated_tokens,o):f}function yO(e){return M(e)&&M(e.context_intent)&&e.context_intent.result_omitted===!0}function dt(e){return bO(e)||yO(e)}function bO(e){return M(e)&&M(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function wO(e,t){let n=t.outputFormat??t.output_format;if(n==="json"||n==="toon")return n;let r=If(e,t)?.encoding;return r?.value==="json"||r?.value==="toon"?r.value: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]="1f954386-76a6-5e03-a0b2-35e5b07c71af")}catch{}})();var EO=4096,OO=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),Lf=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:OO}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Bt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ff(e,t,n=e,r){let o=Object.hasOwn(ee,t)?ee[t]:void 0;if(o?.delivered_row_counters===void 0)return;let i=o.paths[0],s=e[i],a=n[i];if(!Array.isArray(s)||!Array.isArray(a))return;let c=r??a.length,d=a.slice(Math.max(0,c-s.length),c);for(let l of o.delivered_row_counters)typeof e[l.key]=="number"&&(e[l.key]=d.filter(u=>Bt(u)&&u[l.field]===l.equals).length)}function Ln(e){return Array.isArray(e)?e.map(Ln):Bt(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Ln(n)])):e}function Hf(e,t){if(!Bt(e))return Ln(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Bt(i)?[o,Ln(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Ln(a)]))]))}function SO(e,t){return Array.isArray(e)?e.map(n=>Hf(n,t)):Hf(e,t)}function bo(e,t,n){let r=n?Lf[n]:void 0,o=r?.paths.includes(e)===!0;return vO("sha256").update(A({path:e,value:o?SO(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function ea(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint,...e.direction==="backward"?{d:"b"}:{}}),"utf8").toString("base64url")}function kO(e){return typeof e=="string"&&(we(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function AO(e){return e===void 0||e==="b"}function IO(e){if(Tr(e))throw new y("The read-output continuation cursor was shortened by output compaction: it contains an ellipsis, which no cursor encoder emits.",g.USAGE,{code:"read_output_cursor_invalid",reason:"cursor_compacted",required:"Pass the whole cursor the previous page emitted; a shortened cursor cannot resume the read.",nextSteps:["Re-read the previous page with a larger --output-budget (or --output-budget unbounded) and pass its whole output_cursor to --output-cursor."]})}function lt(e){if(IO(e),e.length>EO)throw new y("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!Bt(t)||t.v!==1||!kO(t.c)||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0||!AO(t.d))throw new y("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f,...t.d==="b"?{direction:"backward"}:{}}}function Uf(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Bt(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function TO(e,t,n,r){let o=ge(e).find(c=>c.path===n.path);if(!o)return!1;let i=r?.get(n.path)??o,s=Array.isArray(i.value)?i.value.length:Object.keys(i.value).length,a=be(t,n.path);return s!==n.total_rows||n.offset>s||a!==(n.direction==="backward")?!1:bo(n.path,i.value,t)===n.fingerprint}function zf(e,t,n,r){if(!n)return e;if(n.command!==t)throw new y(`The read-output cursor belongs to ${n.command}, not ${t}.`,g.USAGE,{code:"read_output_cursor_command_mismatch"});if(!TO(e,t,n,r))throw new y("The read-output continuation no longer matches the declared row collection; restart the bounded read.",g.USAGE,{code:"read_output_cursor_stale"});if(!be(t,n.path))return Fs(e,n.path,n.offset);let o=Fs(e,n.path,0,n.offset);for(let s of["count","returned_count"])typeof o[s]=="number"&&(o[s]=n.offset);let i=ee[t].total_key;return typeof o[i]!="number"&&(o[i]=n.total_rows),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]="9c5d8732-3e10-5224-a558-e870397090f2")}catch{}})();var ra=1,Bf=4096,CO=/^[A-Za-z0-9_-]+$/;function na(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function c1(e,t){let n=[...Object.values(vr),...Er],r=new Set(n.flatMap(o=>[na(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){r.add(na(o.flag));for(let i of o.aliases??[])r.add(na(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!r.has(o)))}function d1(e,t){return RO("sha256").update(e).update("\0").update(A(t)).digest("hex").slice(0,24)}function jn(e,t,n,r){return Buffer.from(JSON.stringify({version:ra,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function ut(e,t){return new y(e,g.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${t} to obtain a fresh cursor.`]})}function xO(e){return new y("Query cursor was shortened by output compaction: it contains an ellipsis, which no cursor encoder emits.",g.USAGE,{code:"invalid_query_cursor",reason:"cursor_compacted",required:"Pass the whole cursor the previous page emitted; a shortened cursor cannot resume the query.",nextSteps:[`Re-read the previous page with a larger --output-budget (or --output-budget unbounded) and pass its whole next_cursor to ${e}.`,`Or repeat the original query without ${e} to obtain a fresh cursor.`]})}function NO(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===ra&&typeof t.fingerprint=="string"&&typeof t.after_id=="string"&&t.after_id.length>0&&(t.after_index===void 0||Number.isSafeInteger(t.after_index)&&t.after_index>=0)&&(t.snapshot===void 0||typeof t.snapshot=="string"&&t.snapshot.length>0)}function ta(e,t="--after"){if(typeof e!="string")throw ut("Query cursor is malformed.",t);let n=e.trim();if(Tr(n))throw xO(t);if(n.length===0||n.length>Bf||!CO.test(n))throw ut("Query cursor is malformed.",t);let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw ut("Query cursor is malformed.",t)}if(!NO(r)){let o=!1;try{lt(n),o=!0}catch{}throw o?new y(`An output cursor must be continued with --output-cursor, not ${t}.`,g.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${t} with --output-cursor ${n}; retain any producer ${t} cursor from the original page.`]}):ut("Query cursor version or payload is unsupported.",t)}return r}function oa(e,t,n="--after"){let r=ta(e,n);if(r.fingerprint!==t)throw ut(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`,n);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function l1(e,t){return oa(e,t).after_id}function DO(e,t,n,r,o="--after"){if(t===void 0)return 0;let i=oa(t,n,o),s=e.findIndex(a=>r(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw ut(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function u1(e,t){if(t.cursor!==void 0&&oa(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw ut("Query cursor does not match the requested snapshot.","--after");let n=DO(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:jn(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var f1=Object.freeze({version:ra,max_length:Bf});import{randomUUID as LO}from"node:crypto";import{randomUUID as PO}from"node:crypto";import{constants as Vt}from"node:fs";import{lstat as Vf,mkdir as $O,open as Wf,rename as MO,rm as jO}from"node:fs/promises";import wo 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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var ve={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30},L=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function ft(e){let t=Date.parse(e.now??new Date().toISOString());if(!Number.isFinite(t))throw new L("Context usage now must be a valid timestamp");return{iso:new Date(t).toISOString(),ms:t}}function Gf(e){let t=e.maxBytes??ve.max_bytes,n=e.maxEvents??ve.max_events,r=e.retentionDays??ve.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>ve.max_bytes||!Number.isSafeInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new L("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:n,cutoff:ft(e).ms-r*864e5}}async function Kf(e,t){if(!(await Vf(wo.dirname(e))).isDirectory())throw new L("Context usage runtime must be a real directory");try{if((await Vf(e)).isSymbolicLink())throw new L("Context usage ledger must not be a symbolic link")}catch(r){if(!B(r))throw r}let n=await Wf(e,t|Vt.O_NOFOLLOW|Vt.O_NONBLOCK,384);try{let r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new L("Context usage ledger must be an unshared regular file");return n}catch(r){throw await n.close(),r}}async function vo(e){let t=Gf(e);try{let n=await Kf(wo.join(e.pmRoot,"runtime","context-usage.jsonl"),Vt.O_RDONLY);try{let r=(await n.stat()).size,o=Math.max(0,r-t.maxBytes),i=Buffer.alloc(Math.min(r,t.maxBytes)),{bytesRead:s}=await n.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
|
|
80
|
+
`)?a.slice(a.indexOf(`
|
|
81
|
+
`)+1):"":a).split(`
|
|
82
|
+
`).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await n.close()}}catch{return[]}}function qf(e,t,n){let r=[],o=0;for(let i=e.length-1;i>=0&&r.length<n;i-=1){let s=`${JSON.stringify(e[i])}
|
|
83
|
+
`;if(o+=Buffer.byteLength(s),o>t)break;r.push(s)}return r.reverse().join("")}async function Fn(e,t,n){let r=Gf(e),o=wo.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(r.maxBytes*ve.retained_byte_fraction),s=Math.min(ve.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
|
|
84
|
+
`)>s))throw new L("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=r.cutoff),c=qf(a,i,r.maxEvents),d=performance.now(),l=await kn(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await $O(wo.dirname(o),{recursive:!0});let f=await Kf(o,Vt.O_WRONLY|Vt.O_CREAT|Vt.O_APPEND);try{let m=(await f.stat()).size,p=n===void 0?void 0:await vo(e);if(p?.some(E=>E.kind==="delivery"&&E.serve_id===n))return{written_bytes:0,ledger_bytes:m,compacted:!1,lock_wait_ms:u};if(!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&m+Buffer.byteLength(c)<=r.maxBytes)return await f.writeFile(c,"utf8"),{written_bytes:Buffer.byteLength(c),ledger_bytes:m+Buffer.byteLength(c),compacted:!1,lock_wait_ms:u};let h=qf([...p??await vo(e),...a],i,r.maxEvents),_=`${o}.${process.pid}.${PO()}.tmp`,b=await Wf(_,"wx",384);try{try{await b.writeFile(h,"utf8")}finally{await b.close()}return await f.close(),f=void 0,await MO(_,o),{written_bytes:Buffer.byteLength(h),ledger_bytes:Buffer.byteLength(h),compacted:!0,lock_wait_ms:u}}finally{await jO(_,{force:!0})}}finally{await f?.close()}}finally{await 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]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();var FO=864e5,Eo=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function S1(e,t){let n=z(e);n!==null&&t!==null&&(n[Eo]=t)}function Un(e,t){let n=z(e),r=z(t),o=n?.[Eo];r!==null&&o!==void 0&&(r[Eo]=o)}function UO(e){return z(e)?.[Eo]??null}function Xf(e){let t=z(e);for(let n of["read_output","context_intent"])if(z(t?.[n])?.result_omitted===!0)return!0;return!1}function je(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function Jf(e,t){if(Array.isArray(t))for(let n of t)je(e,z(n)?.id)}function Yf(e,t){if(Array.isArray(t))for(let n of t)je(e,n)}function zO(e,t){let n=z(e.recommended)===null?[]:[e.recommended];for(let r of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[r])&&n.push(...e[r]);for(let r of n){let o=z(r);je(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])je(t,z(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])je(t,i)}}function HO(e,t){for(let n of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])Jf(t,e[n]);for(let n of Array.isArray(e.blockers)?e.blockers:[])je(t,z(n)?.blocked_by);BO(e,t)}function BO(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=z(o);je(t,i?.id),Jf(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])Yf(t,z(i)?.items);let n=z(e.agenda);for(let o of Array.isArray(n?.events)?n.events:[])je(t,z(o)?.item_id);let r=z(e.tests);Yf(t,r?.items_failing)}function VO(e,t){let n=z(e);if(n===null||Xf(e))return[];let r=new Set;return t==="next"?zO(n,r):HO(n,r),[...r]}async function k1(e){let t=UO(e.result);if(t===null)return!1;let n=Xf(e.result);return await qO({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:VO(e.result,t.surface),resultOmitted:n}),!0}async function A1(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(o=>!o.id.trim()||!Number.isInteger(o.rank)||o.rank<1))throw new L("Context usage serving requires an author and valid ranked rows");let t=e.rows.map(o=>({id:o.id.trim(),rank:o.rank,included:o.included}));if(new Set(t.map(o=>o.id)).size!==t.length)throw new L("Context usage serving requires unique normalized row ids");let n=t.slice(0,ve.max_serving_rows),r={serve_id:LO(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:n.map(o=>o.id)};return r.storage=await Fn(e,[{kind:"serve",schema_version:2,serve_id:r.serve_id,at:ft(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:n,candidate_count:t.length,omitted_row_count:t.length-n.length,result_omitted:!1,packed_item_ids:n.filter(o=>o.included).map(o=>o.id)}]),r}async function qO(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;let t=new Set(e.receipt.rows.map(i=>i.id)),n=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(n.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&n.length>0)throw new L("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let r=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(i=>i.id)),o={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:ft(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:n.filter(i=>r.has(i))};await Fn(e,[o],o.serve_id)}async function I1(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new L("Context usage touch requires author, itemId, and intent");await Fn(e,[{kind:"touch",at:ft(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function T1(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new L("Context usage touch requires author and intent");let r=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new L("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new L("Context usage touch requires non-empty itemId");r.add(a)}let o=ft(e).iso,i=[...r].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:n}));await Fn(e,i)}function WO(e,t,n,r){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=n&&i-n<=r)?.time}function GO(e,t){let n=new Map;for(let r of e)r.kind==="delivery"&&r.schema_version===2&&r.author===t&&!n.has(r.serve_id)&&n.set(r.serve_id,r);return n}async function R1(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};let t=await vo(e),n=ft(e).ms,r=(e.horizonHours??24)*36e5;if(![Number.isFinite(r),r>0].every(Boolean))throw new L("Context usage horizonHours must be positive");let o=e.author.trim(),i=t.filter(f=>f.kind==="touch").filter(f=>f.author===o).map(f=>({entry:f,time:Date.parse(f.at)})),s=new Map,a=0,c=0,d=0,l=GO(t,o);t.filter(f=>f.kind==="serve").filter(f=>f.author===o).forEach(f=>{if(![f.schema_version===2,!!f.serve_id].every(Boolean)){c+=1;return}a+=1;let m=Date.parse(f.at),p=l.get(f.serve_id),h=new Set(p?.delivered_item_ids??[]);for(let _ of f.rows){if(!h.has(_.id))continue;let b=WO(i,_.id,m,r);if(b===void 0)continue;d+=1;let E=Math.max(0,(n-b)/FO);s.set(_.id,(s.get(_.id)??0)+Math.exp(-E/14))}});let u=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([f,m])=>[f,u===0?.05:.05+.95*m/u])),positive_judgments:d,serving_events:a,untrusted_serving_events:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a64c599a-e4c7-5f37-8ef6-fad2f7a9fd20")}catch{}})();var YO="limit_overridden_by_intent",tm=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),nm=new KO;function XO(){return nm.getStore()??tm}function B1(e,t){return nm.run(QO(e.workspaceContracts,e.packageContracts),t)}function JO(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))throw new TypeError(`Invalid context intent command or name: ${o}`);if(e.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(e.token_budget)||e.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);let i=[...new Set(e.included_field_groups.map(s=>s.trim()).filter(Boolean))];if(i.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function QO(e=[],t=[]){let n=[{source:"core",contracts:tm,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=JO(s,i.source),c=`${a.command}:${a.intent}`;if(o.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);if(o.add(c),!i.allowOverride&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function rm(e,t,n=XO(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let m=Array.from({length:i.length+1},(p,h)=>h);for(let p=1;p<=f.length;p+=1){let h=m[0];m[0]=p;for(let _=1;_<=i.length;_+=1){let b=m[_];m[_]=Math.min(m[_]+1,m[_-1]+1,h+(f[p-1]===i[_-1]?0:1)),h=b}}return{candidate:f,distance:m[i.length]}}).sort((f,m)=>f.distance-m.distance||f.candidate.localeCompare(m.candidate))[0].candidate,d=[o,...r,"--for",i],l=[o,...r,"--for",c],u=oe(l);throw new y(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,g.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:oe(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}function ia(e,t){let n=pt(e.limit),r=String(n===void 0?t:Math.min(n,t));return(e.limit===void 0||n!==void 0)&&(e.limit=r),r}var om={context:(e,t,n,r)=>{e.section===void 0&&e.depth===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard");let o=So(r,e.tokenBudget,t.token_budget),i=ko("context",t.intent,o,n),s=ia(e,i);e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n,r)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let o=So(r,e.tokenBudget,t.token_budget),i=ko("list",t.intent,o,n);ia(e,i)},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n,r)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let o=So(r,e.tokenBudget,t.token_budget),i=ko("search",t.intent,o,n);ia(e,i)}};function V1(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==void 0&&(e==="get"||e==="list"||e==="search"))throw new y("--token-budget requires a declared context intent selected with --for",g.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let c={...t,tokenBudget:r};return delete c.token_budget,c}let o=rm(e,t.for,void 0,n),i=zn(t),s=pt(r)!==void 0||typeof i=="number",a={...t};return a.tokenBudget===void 0&&r!==void 0&&(a.tokenBudget=r),delete a.token_budget,typeof i=="number"?a.tokenBudget=String(i):a.tokenBudget===void 0&&(a.tokenBudget=String(o.token_budget)),om[e](a,o,s,i),a}var ZO={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Oo=256;function sa(e,t,n=!0,r=!0){return Array.isArray(e)?e.map(o=>sa(o,t,n,!1)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([o,i])=>[o,n&&typeof i=="string"&&ln(o)?i:sa(i,t,n&&!(r&&Ir(t,o)),!1)])):typeof e=="string"?Ar(e):e}function pt(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function zn(e){let t=e.outputBudget??e.output_budget;return t==="unbounded"?t:pt(t)}function eS(e){return zn(e)===void 0?"--token-budget":"--output-budget"}function So(e,t,n){return typeof e=="number"?e:tS(t,n)}function tS(e,t){let n=pt(e);if(n===void 0)return t;if(n<Oo)throw new y(`Context intent token budget must be at least ${Oo}`,g.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Oo}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Oo} or omit the override.`]});return n}function im(e,t){return e==="context"?e==="context"&&t==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:e==="list"?520:480,rowCost:16}}function ko(e,t,n,r){if(e==="get"||e==="next")return;let{overhead:o,rowCost:i}=im(e,t),s=Math.max(e==="context"?1:2,Math.floor((n-o)/i));return r?s:Math.min(e==="context"?20:100,s)}function _t(e,t,n){let r=it(n),o=n.outputRowContract===!0||n.output_row_contract===!0,i=t.estimated_tokens,s=i;for(let a=0;a<Bs;a+=1){t.estimated_tokens=i;let c=ye(o||!Object.hasOwn(e,"row_contract")?e:Object.fromEntries(Object.entries(e).filter(([d])=>d!=="row_contract")),r);if(c===i)return;i=c,s=Math.max(s,i)}t.estimated_tokens=s}var Qf={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function sm(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.fingerprint!="string"||!Number.isSafeInteger(t.after_index)?void 0:{fingerprint:t.fingerprint,after_index:t.after_index,...typeof t.snapshot=="string"?{snapshot:t.snapshot}:{}}}catch{return}}function nS(e){if(e===null||typeof e!="object")return;if(typeof e.id=="string")return e.id;let t=e.item?.id;return typeof t=="string"?t:void 0}function rS(e,t,n,r){let o=!1;for(;;){if(_t(e,t,r),t.estimated_tokens<=t.token_budget||n.length<=1)return o;let i=Buffer.byteLength(JSON.stringify(n),"utf8"),s=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(s/Math.max(1,Math.ceil(i/n.length)))))),o=!0}}function oS(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=sm(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=rS(e,t,r,n)||d,!d)return!1;let l=nS(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),_t(e,t,n),!1;if(e.next_cursor=jn(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),_t(e,t,n),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function iS(e,t,n,r){if(e==="list"||e==="search")return oS(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(_t(t,n,r),n.estimated_tokens<=n.token_budget)return o;let i=Qf[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,m)=>m.rows.length-f.rows.length||f.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=Qf[e].reduce((f,m)=>f+(Array.isArray(t[m])?t[m].length:0),0);if(s<=1)return o;let a=Math.min(i.rows.length,s-1),c=Buffer.byteLength(JSON.stringify(i.rows),"utf8"),d=Math.max(1,Math.ceil(c/i.rows.length)),l=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function aa(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in om))return n;let o=r,i=rm(o,t.for),s=zn(t),a=So(s,t.tokenBudget??t.token_budget,i.token_budget),c={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:a,declared_token_budget:i.token_budget,token_budget_override:a-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:ZO[o],declaration_feasible:!0,result_omitted:!1},d={...n},l=ko(o,i.intent,c.token_budget,pt(t.tokenBudget??t.token_budget)!==void 0||typeof s=="number");if(l!==void 0){let h=pt(t.limit),_=h!==void 0&&h<l;c.budget_derived_limit=l,c.binding_constraint=_?"explicit_limit":"token_budget",c.limit_reason=_?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",d.budget_derived_limit=l,lS({builtInCommand:o,intent:i.intent},c,d,t)}let u=ua.get(t)??0,f=c.token_budget;c.token_budget=f-u;let m=s==="unbounded"?ca(d,c,t):sS(o,d,c,t,we(e,t));c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget;let p=am(s,c,m,()=>dm(e,o,i.intent,{...c,token_budget:f,estimated_tokens:c.estimated_tokens+u},d,t));return c.result_omitted&&(c.estimated_tokens+=u,c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget),c.token_budget=f,p}function ca(e,t,n){let r={...e,context_intent:t};return _t(r,t,n),r}function sS(e,t,n,r,o){let i=ca(t,n,r);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",i=ca(sa(t,o),n,r)),n.estimated_tokens>n.token_budget&&iS(e,i,n,r)&&(n.degradation="budget_row_compaction",_t(i,n,r)),i}var ua=new WeakMap;function am(e,t,n,r){return t.estimated_tokens<=t.token_budget||(t.within_budget=!1,e==="unbounded")?n:(t.degradation="budget_receipt_only",t.result_omitted=!0,typeof e=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:t}:{budget_exceeded:{omitted_result:!0,reason:t.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:r()},context_intent:t})}var aS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function Zf(e,t){if(typeof e.after!="string"||e.after.length===0||dt(t))return t;let n=sm(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of aS)delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cS(e,t){let n=e==="get"&&te(t.item)&&typeof t.item.id=="string"?t.item.id:e==="search"&&typeof t.query=="string"?t.query:void 0;return n===void 0?"":` ${cm(n)}`}function cm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function dS(e){return typeof e.fields=="string"&&e.fields.trim()!==""?` --fields ${cm(e.fields)}`:""}function lS(e,t,n,r){let o=pt(r.limit),i=t.budget_derived_limit;if(o===void 0||o<=i)return;let{overhead:s,rowCost:a}=im(e.builtInCommand,e.intent),c=Math.max(t.token_budget,s+a*o);t.limit_reason=`The ${t.token_budget}-token ${e.intent} budget carries ${i} rows, so it reduced the caller's --limit ${o}.`,t.limit_override={flag:"--limit",requested:o,effective:i,...Number.isSafeInteger(c)?{token_budget_for_requested:c,restore_with:`${eS(r)} ${c}`}:{}};let d=`${YO}:--limit ${o}->${i}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,d]:[d],te(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function dm(e,t,n,r,o,i){let s=cS(t,o),a=t==="get"?"":` --limit ${r.budget_derived_limit??1}`,{output_budget:c}=Dn({effective_budget_tokens:r.token_budget,measured_result_tokens:r.estimated_tokens});return`pm ${e}${s}${dS(i)} --for ${n} --token-budget ${c}${a}`}function mt(e,t){if(te(e))return typeof e[t]=="number"?e[t]:void 0}function em(e,t){let n=e;for(let r=0;r<8;r+=1){uS(n);let o=mt(n.context_intent,"estimated_tokens"),i=mt(n.read_output,"estimated_tokens"),s=mt(n.read_session,"spent_this_call_tokens");if(te(n.context_intent)&&n.context_intent.result_omitted!==!0&&_t(n,n.context_intent,t),n=Zs(n,t),mt(n.context_intent,"estimated_tokens")===o&&mt(n.read_output,"estimated_tokens")===i&&mt(n.read_session,"spent_this_call_tokens")===s)break}return n}function uS(e){let t=e.context_intent;te(t)&&Number(t.estimated_tokens)>Number(t.token_budget)&&(t.within_budget=!1)}function fS(e,t){let n=t.context_intent;if(!te(n)||n.result_omitted===!0)return;let r=n.degradation==="recursive_budget_compaction"||n.degradation==="budget_row_compaction",o={...t};for(let i of ge(e)){let s=t[i.path];if(Array.isArray(s)&&Array.isArray(i.value)&&s.length<=i.value.length){let a=i.value.slice(0,s.length);o[i.path]=r?a.map(da):a}}return o}function da(e){return Array.isArray(e)?e.map(da):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,da(n)])):e}function mS(e,t,n){let r=Fu(e,zu(e??"",n));if(typeof r!="object"||r===null||Array.isArray(r))return Un(n,r),r;let o=e??"",i=r,s=aa(o,t,i),a=mt(s.context_intent,"estimated_tokens"),c=fS(i,s),d=Ao(o,t,n,s,c),l=la(t,d,s.context_intent);if(l===void 0)return pS(t,d,s)?hS(o,t,n,i,s,Number(a),c,d):d;let u={...t};ua.set(u,l.estimated-Number(a));let f=aa(o,u,i),m=lm(o,t,u,n,f,c),p=m===void 0?l:la(t,m,f.context_intent);if(p===void 0)return m;let h={...p.receipt,estimated_tokens:p.estimated};return Ao(o,{...t,outputCursor:void 0,output_cursor:void 0},n,am(zn(t),h,m??d,()=>dm(o,h.command,h.intent,h,i,t)))}function pS(e,t,n){let r=n.context_intent;return Object.hasOwn(t,"output_budget_exceeded")&&te(r)&&r.result_omitted!==!0&&_S.has(String(r.command))&&(e.outputInclude??e.output_include)===void 0&&(e.outputSession??e.output_session)===void 0}var _S=new Set(["list","search"]);function hS(e,t,n,r,o,i,s,a){let c=Ao(e,{...t,outputBudget:"unbounded"},n,{...o,context_intent:{...o.context_intent}},s),d={...t};ua.set(d,ye(c,it(t))-i);let l=aa(e,d,r),u=lm(e,t,d,n,l,s);return u===void 0||Object.hasOwn(u,"output_budget_exceeded")||la(t,u,l.context_intent)!==void 0?a:u}function lm(e,t,n,r,o,i){return dt(o)||gS(t,o)?void 0:Ao(e,n,r,o,i)}function gS(e,t){let n=e.outputCursor??e.output_cursor;if(typeof n!="string")return!1;let r=lt(n),o=t[r.path];return Array.isArray(o)&&o.length<=r.offset}function la(e,t,n){let r=te(t.context_intent),o=r?t.context_intent:n;if(!te(o)||o.result_omitted===!0||Object.hasOwn(t,"output_budget_exceeded"))return;let i=o,s=r?i.estimated_tokens:ye(t,it(e));return zn(e)==="unbounded"||s<=i.token_budget?void 0:{receipt:i,estimated:s}}function yS(e){return!te(e)||e.result_omitted===!0?{}:{mirrorEstimate:(t,n)=>{te(t.context_intent)&&(t.context_intent.estimated_tokens=n)}}}function Ao(e,t,n,r,o){let i={...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0};ef(i,{...o===void 0?{}:{continuationBinding:Zf(t,o)},...yS(r.context_intent)});let s=jf(e,i,Zf(t,r));if(Un(n,s),t.outputRowContract===!0||t.output_row_contract===!0||!Object.hasOwn(s,"row_contract"))return te(s.context_intent)?em(s,t):s;let a=Object.fromEntries(Object.entries(s).filter(([d])=>d!=="row_contract"));Object.defineProperty(a,"row_contract",{value:s.row_contract,enumerable:!1,configurable:!0});let c=em(a,t);return delete c.row_contract,Un(s,c),c}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb1266f3-8375-586f-87c6-356cf7843969")}catch{}})();var qt=["result_rows","envelope","diagnostics","hints"],bS=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,wS=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,vS=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,ES=8;function fa(e){return Buffer.byteLength(e,"utf8")}function um(e){return fa(JSON.stringify(e)??"null")}function OS(e,t){return wS.test(e)?"diagnostics":vS.test(e)?"hints":bS.test(e)||Array.isArray(t)?"result_rows":"envelope"}function SS(e){let t={result_rows:0,envelope:0,diagnostics:0,hints:0};if(typeof e!="object"||e===null||Array.isArray(e))return t[Array.isArray(e)?"result_rows":"envelope"]=um(e),t;for(let[n,r]of Object.entries(e))t[OS(n,r)]+=um({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function kS(e,t){let n=qt.reduce((s,a)=>s+t[a],0),r=qt.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-qt.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||qt.indexOf(a.section)-qt.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function fm(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function AS(e,t){let n=fa(t(e)),r=kS(n,SS(e)),o=Object.fromEntries(qt.map(a=>[a,{bytes:r[a],estimated_tokens:at(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:at(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=fm(e,i);for(let a=0;a<ES;a+=1){let c=fa(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:at(c)},s=fm(e,i)}return 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]="787e6c05-d503-5602-a173-e6a59699cea6")}catch{}})();var K1=Object.freeze({comments:Object.freeze(["comments"]),notes:Object.freeze(["notes"]),learnings:Object.freeze(["learnings"])});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e86e884-98ca-5b28-838b-db3543051112")}catch{}})();var mm=new Set(["body","item_hash","linked","claim_state","children","schedule","blockers"]),X1=new Set(["linked","claim_state","children","schedule"]);import{encode as ha}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]="bafcd4e4-ec0f-5340-89ce-b85d822b2323")}catch{}})();function pm(e,t={}){let n=[...new Set(e.flatMap(l=>Object.keys(l)))],r=t.compact?n.filter(l=>e.every(u=>Object.hasOwn(u,l)&&u[l]===null)):[],o=t.compact?n.filter(l=>e.every(u=>{if(!Object.hasOwn(u,l))return!0;let f=u[l];return Array.isArray(f)&&f.every(m=>typeof m=="string"&&m!==""&&!m.includes(";"))})):[],i=new Set(o),s=new Set(r),a=n.filter(l=>!i.has(l)&&e.some(u=>{let f=u[l];return f!==null&&typeof f=="object"})),c=new Set(a),d=[];return{rows:e.map((l,u)=>Object.fromEntries(n.filter(f=>!s.has(f)).map(f=>{if(!Object.hasOwn(l,f))return d.push([u,f]),[f,null];let m=l[f];return i.has(f)?[f,m.join(";")]:[f,c.has(f)?JSON.stringify(m):m]}))),encoding:{json_columns:a,absent:d,...o.length?{list_columns:Object.fromEntries(o.map(l=>[l,";"]))}:{},...r.length?{null_columns:r,null_column_index:r.map(l=>n.indexOf(l))}:{}}}}function _m(e){let{json_columns:t,absent:n,...r}=e,o=new Map;for(let[i,s]of n){let a=o.get(s)??[];a.push(i),o.set(s,a)}return{...t.length>0?{json_columns:t}:{},...o.size>0?{absent_rows:Object.fromEntries(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]="43d2915b-7301-5e96-89e0-51c8e817789e")}catch{}})();function le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var IS=new Set(["brief","compact","fields"]);function hm(e){if(!le(e))return!1;let t=e.fields;return IS.has(e.mode)&&Object.keys(e).length===2&&Array.isArray(t)&&t.length>0&&t.every(n=>typeof n=="string"&&n.length>0)}function gm(e,t){return e.every(n=>le(n)&&Object.keys(n).length===t.fields.length&&t.fields.every(r=>Object.hasOwn(n,r)))}function ym(e,t){return e.mode==="fields"&&t===0?{projection:e}:{}}function bm(e,t){return typeof e.has_more=="boolean"&&e.truncated===e.has_more&&e.count===t&&typeof e.total=="number"&&Number.isSafeInteger(e.total)&&(e.has_more?e.total>t&&typeof e.next_cursor=="string"&&e.next_cursor.length>0:e.total===t&&e.next_cursor==null)}function TS(e){return le(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function ma(e,t="full_item_fields"){if(!le(e)||!Array.isArray(e.omitted_field_groups))return!1;let n=e.omitted_field_groups,r=n[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&n.length===1&&le(r)&&Object.keys(r).length===2&&r.name===t&&r.restore_with==="--full"}function wm(e){if(!le(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!hm(e.projection)||!gm(e.items,e.projection)||!TS(e.completeness)||!bm(e,e.items.length)||!ma(e.omission_receipt))return e;let{total:t,has_more:n,truncated:r,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,filters:l,...u}=e,f=i.status==="complete"&&!n&&Object.keys(i).length===3,{unreadable_item_count:m,unreadable_directory_count:p,...h}=i;return{...u,...f?{}:{total:t,has_more:n,completeness:h},...n?{next_cursor:o}:{},...xS(d),...vm(l,u.applied_limit,s),...ym(s,e.items.length),details:"--full"}}function RS(e){return le(e)&&e.sort==="default"&&e.order==="asc"&&Object.keys(e).every(t=>t==="sort"||t==="order"||t==="effective_keys")}function CS(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&(e[1]==="asc"||e[1]==="desc")}function xS(e){if(!RS(e))return{sorting:e};let t=e.effective_keys;return t===void 0?{}:!Array.isArray(t)||!t.every(CS)?{sorting:e}:{sorting:{effective_keys:t.map(([n,r])=>`${n} ${r}`).join(", ")}}}function NS(e,t){if(typeof e!="string"||t===void 0)return!1;let n=e.split(",").map(r=>r.trim()).filter(Boolean);return n.length===t.fields.length&&n.every((r,o)=>r===t.fields[o])}function vm(e,t,n){if(!le(e))return e===void 0?{}:{filters:e};let r=Object.fromEntries(Object.entries(e).filter(([o,i])=>!(o==="limit"&&String(i)===String(t))&&!(o==="fields"&&NS(i,n))&&!(o==="runtime_filters"&&le(i)&&Object.keys(i).length===0)));return Object.keys(r).length===0?{}:{filters:r}}function DS(e,t){return e.count===t&&!Object.hasOwn(e,"has_more")&&!Object.hasOwn(e,"truncated")&&e.next_cursor==null&&(e.total===void 0||e.total===t)}function PS(e){if(!Object.hasOwn(e,"projection"))return ma(e.omission_receipt,"projection_metadata")?{}:void 0;let t=e.projection;return hm(t)&&t.mode==="fields"&&gm(e.items,t)&&typeof e.now=="string"&&ma(e.omission_receipt)?{projection:t}:void 0}function Em(e){if(!le(e)||typeof e.query!="string"||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!(bm(e,e.items.length)||DS(e,e.items.length)))return e;let t=PS(e);if(t===void 0)return e;let{truncated:n,omission_receipt:r,filters:o,projection:i,now:s,mode_source:a,...c}=e;return{...c,...a==="settings"||t.projection===void 0&&a!==void 0?{mode_source:a}:{},...vm(o,c.applied_limit,t.projection),...t.projection?ym(t.projection,e.items.length):{},details:"--full"}}import{isBoxedPrimitive as $S}from"node:util/types";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();var Om=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function r$(e){return e.replaceAll(Om,"\uFFFD")}function MS(e,t,n){return n&&/^\d+$/u.test(t)?`${e}[${t}]`:/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function pa(e,t,n){if(typeof e=="string"){let r=e.search(Om);return r<0?void 0:{field:t,index:r}}if(!(e===null||typeof e!="object"||n.has(e))){n.add(e);for(let[r,o]of Object.entries(e)){let i=MS(t,r,Array.isArray(e)),s=pa(r,`${i} (key)`,n)??pa(o,i,n);if(s)return s}}}function Sm(e,t,n){if(e===null||typeof e!="object")return e;if($S(e)||typeof e.toJSON=="function")return JSON.parse(JSON.stringify({[t]:e}))[t];if(n.has(e))return n.get(e);let r=Array.isArray(e)?new Array(e.length):{};n.set(e,r);for(let o of Object.keys(e))Object.defineProperty(r,o,{value:Sm(e[o],o,n),enumerable:!0,configurable:!0,writable:!0});return r}function _a(e){let t=Sm(e,"",new WeakMap),n=pa(t,"$",new WeakSet);return n&&jS(n),t}function jS(e){throw new y(`Output field ${e.field} contains an unpaired surrogate code unit at index ${e.index}; structured output requires well-formed Unicode.`,g.USAGE,{code:"text_unpaired_surrogate",field:e.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function o$(e){_a(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]="f33393ac-6b72-5e46-92a5-f276d1fbfff1")}catch{}})();var I$=new Set(Object.values(g)),FS=new Map([["notes_count","notes"],["tests_count","tests"]]);var km=!1;function R(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ga(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function US(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function zS(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function ya(e){if(e==="stdout"){US();return}zS()}function Am(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function HS(){km||(km=!0,process.stdout.on("error",e=>{if(ga(e)){ya("stdout");return}Am(e)}),process.stderr.on("error",e=>{if(ga(e)){ya("stderr");return}Am(e)}))}function BS(e,t){HS();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(ga(n))return ya(e),!1;throw n}}function Ro(e){return BS("stderr",e)}function Tm(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function ba(e,t){let n=" ".repeat(t);return e.split(`
|
|
85
|
+
`).map(r=>`${n}${r}`).join(`
|
|
86
|
+
`)}function VS(e){let t=new Set,n=0;for(let r of e){let o=Object.keys(r);n+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=n*2}function qS(e,t,n,r){let o=" ".repeat(n);if(!R(t)&&!Array.isArray(t))return`${o}${e}: ${Tm(t)}`;let i=e==="omission_receipt"?WS(t,n):void 0;if(i!==void 0)return i;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let s=ba(ha({[e]:t}),n);return r&&t.length>=1&&t.every(R)&&VS(t)?[!1,!0].map(a=>{let c=pm(t,{compact:a});return ba(ha({[e]:c.rows,[`${e}_encoding`]:_m(c.encoding)}),n)}).reduce((a,c)=>Buffer.byteLength(c)<Buffer.byteLength(a)?c:a,s):s}return R(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
|
|
87
|
+
${Io(t,n+1)}`}function WS(e,t){let n=" ".repeat(t);if(nk(e))return`${n}omission_receipt: complete`;let r=R(e)?GS(e):void 0;if(r===void 0)return;let o=`${n}omission_receipt:
|
|
88
|
+
${Io(e,t+1)}`,i=`${n}omission_receipt:
|
|
89
|
+
${Io(r,t+1)}`;return Buffer.byteLength(i)<Buffer.byteLength(o)?i:o}function GS(e){let t=e.omitted_field_groups;if(!Array.isArray(t)||t.length===0||Object.hasOwn(e,"restore_with"))return;let n=[],r;for(let o of t){if(!R(o)||Object.keys(o).length!==2)return;let{name:i,restore_with:s}=o;if(typeof i!="string"||i.length===0||typeof s!="string"||!s.endsWith(i))return;let a=s.slice(0,s.length-i.length);if(r!==void 0&&a!==r)return;r=a,n.push(i)}return Object.fromEntries(Object.entries(e).flatMap(([o,i])=>o==="omitted_field_groups"?[[o,n],["restore_with",`${r}<name>`]]:[[o,i]]))}function KS(e,t,n){let r=e.map(o=>ht(o,t,n||t.preserveRowFacts&&R(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function ht(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return KS(e,t,n);if(R(e)){let r=[],o=Object.entries(e).filter(([i,s])=>{let a=FS.get(i);return!t.omitDuplicateCountAliases||a===void 0||!R(e.collection_counts)||s!==e.collection_counts[a]});for(let[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){r.push([i,[]]);continue}let a=ht(s,t,n);a!==void 0&&r.push([i,a])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function Io(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":ba(ha(e),t);if(R(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>qS(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&R(e.verdict)&&e.verdict.authority==="ok"))).join(`
|
|
90
|
+
`)}return`${n}${Tm(e)}`}var YS=new Set(["filters","now","projection","sorting"]);function XS(e){let t=ht(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!R(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!YS.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function JS(e){return!R(e)||e.ok!==!0||!R(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(QS)}}function QS(e){if(!R(e)||e.ok!==!0||!R(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...n}=e;return n}function Ju(e,t,n=!1,r={}){if(e=_a(e),t==="json"){let i=n?XS(e):e,s=R(e)&&R(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(i,null,s?void 0:2)}
|
|
91
|
+
`}let o=ek(e,ZS(e,ht(JS(Em(wm(e))),To),r.preserveEmptyItemCollections===!0),r.positionalRowPaths??[]);return o===void 0?`{}
|
|
92
|
+
`:`${Io(o,0)}
|
|
93
|
+
`}var To={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function wa(e,t,n=!1){if(Array.isArray(e)){if(e.length===0)return[];let i=Array.isArray(t)?t:[],s=i.length===e.length,a=0,c=e.flatMap(d=>{let l=n||R(d),u=!s&&ht(d,To,l)===void 0,f=wa(d,u?void 0:i[a++],l);return f===void 0?[]:[f]});return c.length>0?c:t}if(!R(e))return t;let r=R(t)?t:{},o=Object.entries(e).flatMap(([i,s])=>{let a=wa(s,Object.hasOwn(r,i)?r[i]:void 0,n);return a===void 0?[]:[[i,a]]});return o.length>0||Object.keys(e).length===0?Object.fromEntries(o):t}function ZS(e,t,n){if(!n||!R(e))return t;let r=R(t)?t:{},o=new Map(Object.keys(e).filter(i=>i==="item"||mm.has(i)).map(i=>[i,wa(e[i],r[i])]));return Rm(e,r,o)}function Rm(e,t,n){let r=Object.entries(t).map(([i,s])=>[i,n.has(i)?n.get(i):s]),o=Object.keys(e);for(let[i,s]of n){if(Object.hasOwn(t,i)||s===void 0)continue;let a=new Set(o.slice(o.indexOf(i)+1)),c=r.findIndex(([d])=>a.has(d));r.splice(c===-1?r.length:c,0,[i,s])}return Object.fromEntries(r)}function ek(e,t,n){if(!R(e))return t;let r=n.filter(s=>{let a=e[s];return Array.isArray(a)&&a.some(c=>ht(c,To,R(c))===void 0)});if(r.length===0)return t;let o=R(t)?t:{},i=new Map(r.map(s=>[s,e[s].map(a=>ht(a,To,!0))]));return Rm(e,o,i)}var tk=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function nk(e){let t=Object.entries(Object(e)).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(Object.fromEntries(t))===tk}function T$(e){let t=Im("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Ro(n.endsWith(`
|
|
94
|
+
`)?n:`${n}
|
|
95
|
+
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var rk=Wt.join("runtime","history-drift-cache.json"),Cm={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 xm(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function ok(e){let t=Wt.join(e,rk),n=!1,r="invalid_cache_path";try{n=(await va.stat(await va.realpath(e))).isDirectory()}catch(o){let i=xm(o);r=i===void 0?"unknown":Cm[i]??"filesystem_error"}if(!n){Ro(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
96
|
+
`);return}try{await va.rm(t,{force:!0})}catch(o){let i=xm(o);if(B(o))return;let s=i===void 0?"unknown":Cm[i]??"filesystem_error";Ro(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
97
|
+
`)}}async function Co(e){let t=Wt.dirname(Wt.resolve(e));Wt.basename(t)==="history"&&await ok(Wt.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]="d7f91395-3d21-5046-a8df-e383d66eace9")}catch{}})();var sk={front_matter:{},body:""},et=3,En=[1,2,3],ak=1,jm=[1];function Lm(e){return ce(A(e),e.hash_algorithm)}function Gt(e){return At(A(e))}function Z$(e){return At(A(e))}function ka(e){let t={...e,record_hash_version:ak},{record_hash:n,...r}=t;return{...t,record_hash:Lm(r)}}function eM(e){let t=e.record_hash_version;return typeof t=="number"&&Number.isInteger(t)&&t>Math.max(...jm)&&typeof e.record_hash=="string"&&e.record_hash.length>0}function Zr(e){try{re(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!jm.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return Lm(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function ck(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Gt(e.patch)};return e.hash_algorithm!==void 0&&(n.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function hs(e,t,n={}){let r=Zr(e);if(!r.ok)throw new TypeError(r.error);let o=Gt(e.patch),i=n.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Gt(t.patch),s=ka({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],ck(e,n)]}:{}}),a=gs(s);if(!a.ok)throw new TypeError(a.error);return s}function Fm(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!gt(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function Um(e){return gt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&Fm(e.patch)}function Zl(e){return Um(e)}function dk(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function lk(e){return!gt(e)||!dk(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!Fm(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||Um(e.record)}function uk(e){try{for(let t of e){if(!lk(t))return!1;re(t.hash_algorithm)}return!0}catch{return!1}}function fk(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Gt(t.patch)===e.patch_hash}function mk(e,t,n){if(t.patch&&Gt(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return fk(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(Gt(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...n.length===0?{}:{reanchor_evidence:n}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,n.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function gs(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!uk(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r],i=mk(n,o,t.slice(0,r));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!Zr(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function xo(e,t){return(e??"").localeCompare(t??"")}function Dm(e,t){return(e??0)-(t??0)}function Le(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function pk(e,t){return[e.scope.localeCompare(t.scope),xo(e.path,t.path),xo(e.command,t.command),Dm(e.timeout_seconds,t.timeout_seconds),xo(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,Le(e.env_clear,t.env_clear,[]),Le(e.env_set,t.env_set,{}),Le(e.assert_stdout_contains,t.assert_stdout_contains,[]),Le(e.assert_stdout_regex,t.assert_stdout_regex,[]),Le(e.assert_stderr_contains,t.assert_stderr_contains,[]),Le(e.assert_stderr_regex,t.assert_stderr_regex,[]),Dm(e.assert_stdout_min_lines,t.assert_stdout_min_lines),Le(e.assert_json_field_equals,t.assert_json_field_equals,{}),Le(e.assert_json_field_gte,t.assert_json_field_gte,{}),xo(e.note,t.note)].find(n=>n!==0)??0}function _k(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function hk(e,t){let n=_k(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:gt(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function gk(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!hk(r,o.path)?{...o,op:"add"}:o;n.push(i),r=Mm.applyPatch(r,[i],!0,!0).newDocument}return n}function No(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=Pt(e),o=t===1||t===2&&n?{...r.metadata,...r.metadata.dependencies===void 0?{}:{dependencies:r.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...r.metadata.tests===void 0?{}:{tests:r.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...r.metadata.test_runs===void 0?{}:{test_runs:r.metadata.test_runs.map(({executions:s,...a})=>a)}}:r.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(pk)}:o;return{front_matter:We(i,ke),body:r.body}}function Pm(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=Pt(e);return{metadata:We(t.metadata,ke),body:t.body}}function Aa(e){return zm(e,et)}function zm(e,t,n){if(!En.some(r=>r===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return ce(A(No(e,t)),n)}function eu(e,t,n){let r=zm(e,t,n);return t===2?[r,ce(A(No(e,t,!0)),n)]:[r]}function tM(){return At(A(sk))}function nM(e){let t=Md(e.op),n=No(e.before,et),r=No(e.after,et),o=Pm(e.before),i=Pm(e.after),s=Mm.compare(o,i),a=gk(o,s),c=Ml(e.author),d=c.harness?Object.fromEntries(Object.entries(Pl().provenance_outcomes).filter(([m,p])=>p.resolver!==void 0&&(p.status!=="resolved"||c.provenance?.[m]?.source==="probe"))):void 0,l=d===void 0||Object.keys(d).length===0?e.context:{...e.context,agent_provenance_outcomes:d},u=e.hashAlgorithm??jd,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??$l(e.author),...c.harness?{agent_harness:c.harness}:{},...c.model?{agent_model:c.model}:{},...c.model_source?{agent_model_source:c.model_source}:{},...c.instance?{agent_instance:c.instance}:{},...c.provenance?{agent_provenance:c.provenance}:{},...c.episode?{agent_episode:c.episode}:{},op:t,patch:a,before_hash:ce(A(n),u),after_hash:ce(A(r),u),item_hash_version:et,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return ka({...f,event_class:jt(f)})}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ea(e){return new y(e,g.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function Hm(e){let t=e.ts.trim();if(t.length===0)return pn();if(!Tt(t))throw Ea("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw Ea("History timestamp must not contain surrounding whitespace");return e.ts}function $m(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!Tt(n))throw Ea("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function Oa(e,t){let n=Hm(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return gt(r)?JSON.stringify($m(r,n)):e}return gt(e)?JSON.stringify($m(e,n)):JSON.stringify(e)}async function yk(e,t,n){if(n===!1)return!0;if(typeof n=="string"){let s=Oa(n,t);return await Sa(e,s),await Co(e),await Is(e),!0}if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e,i=Oa(typeof r.line=="string"?r.line:r.entry??t,t);return await Sa(o,i),await Co(o),await Is(o),!0}async function Sa(e,t){let n;try{n=JSON.parse(t)}catch{n=null}if(!gt(n)||n.op!=="create"){await Mc(e,t);return}await Nm.mkdir(ik.dirname(e),{recursive:!0});try{await Nm.writeFile(e,`${t}
|
|
98
|
+
`,{encoding:"utf8",flag:"wx"})}catch(r){throw r.code!=="EEXIST"?r:new y("This item identity is reserved by an existing history stream.",g.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function rM(e,t){let n=await Kt("history_append",{history_path:e,entry:t});if(n.handled&&await yk(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:Hm(t)},o=ka({...r,hash_algorithm:re(r.hash_algorithm),event_class:jt(r)});await Eu(e,o,async()=>{await Sa(e,Oa(o,o))}),await Co(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]="bc6de6a9-454a-5dda-ab67-8f4a2f5c38d8")}catch{}})();var Ia=new Bm;function mM(e,t){return Ia.run([...Ia.getStore()??[],{...e,pmRoot:Ta.resolve(e.pmRoot)}],t)}var wk=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),vk=globalThis,Hn=vk[wk]??=new Bm;function Yt(e){let t=Ta.resolve(e);try{return bk.native(t)}catch{return t}}function pM(){return{entries:new Map}}function _M(e,t){return Hn.run([...Hn.getStore()??[],e],t)}function hM(e,t,n){let r=Yt(t);if(e.pmRoot!==void 0&&e.pmRoot!==r)throw new y("An expected-revision scope is already bound to another tracker.",g.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=r;for(let{id:o,itemHash:i}of n){let s=e.entries.get(o);if(s!==void 0&&s.declared!==i)throw new y(`Item ${o} has two different expected revisions.`,g.USAGE,{code:"expected_revision_duplicate",item_id:o,required:"Declare at most one expected revision per item."});e.entries.set(o,s??{declared:i,expected:i,checked:!1,committed:!1})}}function gM(e){let t=[...e.entries.entries()];return{checked:t.filter(([,n])=>n.checked).map(([n])=>n),unchecked:t.filter(([,n])=>!n.checked).map(([n])=>n)}}function Ra(e,t){let n=Hn.getStore()??[];if(n.length===0)return[];let r=Yt(e),o=new Set(t.filter(i=>typeof i=="string"));return[...new Set(n.flatMap(i=>i.pmRoot===r?[...o].flatMap(s=>i.entries.get(s)??[]):[]))]}function yM(e){let t=Hn.getStore()??[];if(t.length===0)return[];let n=Yt(e),r=new Map;for(let o of t)if(o.pmRoot===n)for(let[i,s]of o.entries){if(s.expected!==s.declared)return;r.set(i,(r.get(i)??new Set).add(s.expected))}if(![...r.values()].some(o=>o.size>1))return[...r].map(([o,i])=>`${o}=${[...i][0]}`)}function bM(e){let t=Yt(e);return(Hn.getStore()??[]).some(n=>n.pmRoot===t&&n.entries.size>0)}function Ek(e,t,n){let r=Ra(e,[n,t.metadata.id]);r.length>0&&Wm(r,n,Aa(t),!1,e)}function wM(e,t,n){let r=Ra(e,[t]);r.length>0&&Wm(r,t,At(n),!0,e)}var Ok="revision_changed",Sk="document_unreadable";function kk(e,t,n={}){let r=[...n.scopeArgs??[]],o=[...n.outputArgs??["--json"]],i=oe([...r,"get",e,...o]),s=oe([...r,"history",e,"--limit","5",...o]);return{required:t?`Recover ${e} without --expect-hash (${oe([...r,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${i} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[oe([...r,"get",e,"--fields","item_hash",...o]),s],nextSteps:[i,s]}}var Ak=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),Ik=globalThis,Ca=Ik[Ak]??=new WeakMap,Tk=8;function Vm(e){for(let t of qm(e)){let n=Ca.get(t);if(n!==void 0)return n}}function*qm(e){let t=e;for(let n=0;n<Tk&&typeof t=="object"&&t!==null;n+=1){yield t;try{t=t.cause}catch{return}}}function Wm(e,t,n,r,o){for(let i of e)if(i.checked=!0,!(!r&&i.expected===n))throw Nk(o,new y(`Item ${t} is no longer at the expected revision ${i.expected.slice(0,12)}${r?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${i.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,g.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:i.expected,current_revision:n,reason:r?Sk:Ok,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...kk(t,r)}))}function vM(e,t){let n=Vm(e);return n===void 0||n===Yt(t)}var Rk=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),Ck=globalThis,xa=Ck[Rk]??=new WeakSet;function xk(e){for(let t of qm(e))if(xa.has(t))return!0;return!1}function EM(e){return xa.add(e),e}function OM(e,t){let n=Vm(e);return n!==void 0&&Ca.set(t,n),xk(e)&&xa.add(t),t}function Nk(e,t){return Ca.set(t,Yt(e)),t}function SM(e,t,n=t.metadata.id){Ek(e,t,n);for(let r of Do(e,[n,t.metadata.id]))r.validate(t),r.compensation!==void 0&&n===r.id&&(r.compensation.validated_storage_id=n)}function Do(e,t){let n=Ta.resolve(e);return(Ia.getStore()??[]).filter(r=>r.pmRoot===n&&t.includes(r.id))}function kM(e,t,n=t.metadata.id,r=[],o){let i=Ra(e,[n,t.metadata.id,...r]);if(i.length>0){let s=o??Aa(t);for(let a of i)a.expected=s,a.committed=!0}for(let s of Do(e,[n,t.metadata.id,...r]))s.committed?.(t)}function Na(e,t,n){let r=t.filter(o=>o!==void 0);if(!r.some(o=>o!==r[0]))return Do(e,[r[0]]).find(o=>o.compensation?.operations.includes(n)===!0&&o.compensation.validated_storage_id===o.id)?.compensation}function AM(e,t,n){let r=Na(e,t,n);return r===void 0||r.overrides.length===0?{}:{transaction_compensation:{transaction_id:r.transaction_id,step_id:r.step_id,overridden:structuredClone(r.overrides)}}}function IM(e,t){return Object.assign({},...Do(e,t).map(n=>n.historyContext))}import vt from"node:fs/promises";import wt from"node:path";import{pathToFileURL as MA}from"node:url";import Xt from"node:fs";import Fe from"node:path";import{fileURLToPath as Dk}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]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();var Pk="@unbrained/pm-cli";function $k(e){try{return JSON.parse(Xt.readFileSync(e,"utf8")).name===Pk}catch{return!1}}function Mk(e){let t=Xt.existsSync(e)&&Xt.statSync(e).isDirectory()?Fe.resolve(e):Fe.dirname(Fe.resolve(e));for(;;){let n=Fe.join(t,"package.json");if(Xt.existsSync(n)&&$k(n))return t;let r=Fe.dirname(t);if(r===t)return;t=r}}function Da(e,t=[]){let n=Dk(e);return Mk(n)||Fe.resolve(Fe.dirname(n),...t)}function NM(e,t=[]){try{let n=Fe.join(Da(e,t),"package.json");if(!Xt.existsSync(n))return;let r=JSON.parse(Xt.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function Gm(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([n,r])=>[n,r.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[n,r]of Object.entries(t.registrations))e.registrations[n].length=r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var Pa=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60fd882d-7c92-5be5-bf46-7e3c128bfb58")}catch{}})();var jk=new Set(Pa);function Lk(e){if(e!==void 0&&!jk.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${Pa.join(", ")}`)}function Km(e){D("registerCommand definition.action",e.action),D("registerCommand definition.family",e.family),D("registerCommand definition.description",e.description),D("registerCommand definition.intent",e.intent),D("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");Lk(e.family)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="07cb237c-3956-5997-85f8-972d2ee490d0")}catch{}})();function Fk(e){let t=$("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return D("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function Ym(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=Fk(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function $a(e,t,n){return{registration:t,action:n,command:e.command,args:W(e.args),options:W(e.options),global:W(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc2e7eac-cd1c-5885-aa27-e98455008a4f")}catch{}})();function Xm(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function Bn(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ue(e){return fe.includes(e)}function Jm(e){let t=e.trim().toLowerCase();return Ue(t)?t:null}function Qm(e){return e.filter(t=>!Ue(t))}function Ma(e){let t=e.trim().toLowerCase();return t.length===0?null:Rc[t]??null}function Zm(e){let t=Bn([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Ma(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:Bn(n),legacy_aliases:o}}function Uk(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Ma(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of fe){let a=sr(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function ep(e,t,n){let r=fe.join(","),o=Uk(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function tp(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function zk(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Ma(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ei,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function Hk(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...fe],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!Ue(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ei,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb1b4879-079c-50d4-afa5-e8a36ead2e5c")}catch{}})();function ne(e){return typeof e!="string"?"":e.trim().toLowerCase()}function O(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function Bk(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function Jt(e){return new Set((e??[]).map(t=>Bk(t)).filter(t=>t.length>0))}function np(e){let t=ne(e);return er.includes(t)?t:"off"}function rp(e){let t=ne(e);return tr.includes(t)?t:"off"}function Vn(e){let t=ne(e);return nr.includes(t)?t:"none"}function ja(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Cc.includes(t)?t:void 0}function op(e){if(typeof e=="string"){let t=ja(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:ja(e.global)??"block",project:ja(e.project)??"block"}:{global:"block",project:"block"}}function Vk(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function I(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function qk(e){let t=ne(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?Vn(e.sandbox_profile):void 0,allowedCapabilities:O(e.allowed_capabilities),blockedCapabilities:O(e.blocked_capabilities),allowedSurfaces:Jt(e.allowed_surfaces),blockedSurfaces:Jt(e.blocked_surfaces),allowedCommands:O(e.allowed_commands),blockedCommands:O(e.blocked_commands),allowedActions:O(e.allowed_actions),blockedActions:O(e.blocked_actions),allowedServices:O(e.allowed_services),blockedServices:O(e.blocked_services)}}}function ip(e){let t=new Map;for(let n of e??[]){let r=qk(n);r&&t.set(r.name,r.normalized)}return t}function Wk(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of I([...e.allowedCapabilities,...e.blockedCapabilities]))Ue(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of I([...o.allowedCapabilities,...o.blockedCapabilities]))Ue(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(rr);for(let o of I([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of I([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function sp(e){let t=e.extensions?.policy??{},n=O(t.allowed_capabilities),r=O(t.blocked_capabilities),o=Jt(t.allowed_surfaces),i=Jt(t.blocked_surfaces),s=ip(t.extension_overrides);return{mode:np(t.mode),trustMode:rp(t.trust_mode),pmMaxVersionExceededMode:op(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:O(t.trusted_extensions),defaultSandboxProfile:Vn(t.default_sandbox_profile),allowedExtensions:O(t.allowed_extensions),blockedExtensions:O(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:O(t.allowed_commands),blockedCommands:O(t.blocked_commands),allowedActions:O(t.allowed_actions),blockedActions:O(t.blocked_actions),allowedServices:O(t.allowed_services),blockedServices:O(t.blocked_services),overridesByName:s,warnings:Wk({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function ap(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:I(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:I(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:I(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:I(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:I(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:I(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:I(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:I(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:I(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:I(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:Vk(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:I(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:I(e.allowedExtensions),blocked_extensions:I(e.blockedExtensions),allowed_capabilities:I(e.allowedCapabilities),blocked_capabilities:I(e.blockedCapabilities),allowed_surfaces:I(e.allowedSurfaces),blocked_surfaces:I(e.blockedSurfaces),allowed_commands:I(e.allowedCommands),blocked_commands:I(e.blockedCommands),allowed_actions:I(e.allowedActions),blocked_actions:I(e.blockedActions),allowed_services:I(e.allowedServices),blocked_services:I(e.blockedServices),extension_overrides:t}}function cp(e){let t=ip(e.extension_overrides);return{mode:np(e.mode),trustMode:rp(e.trust_mode),pmMaxVersionExceededMode:op(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:O(e.trusted_extensions),defaultSandboxProfile:Vn(e.default_sandbox_profile),allowedExtensions:O(e.allowed_extensions),blockedExtensions:O(e.blocked_extensions),allowedCapabilities:O(e.allowed_capabilities),blockedCapabilities:O(e.blocked_capabilities),allowedSurfaces:Jt(e.allowed_surfaces),blockedSurfaces:Jt(e.blocked_surfaces),allowedCommands:O(e.allowed_commands),blockedCommands:O(e.blocked_commands),allowedActions:O(e.allowed_actions),blockedActions:O(e.blocked_actions),allowedServices:O(e.allowed_services),blockedServices:O(e.blocked_services),overridesByName:t,warnings:[]}}function ze(e,t){return e.overridesByName.get(ne(t))??null}function Qt(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function dp(e,t,n){let r=n.trim().toLowerCase(),o=ze(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return Qt(i,s,r,"capability_not_allowlisted","capability_blocked")}function Gk(e,t,n){let r=ze(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return Qt(o,i,n,"surface_not_allowlisted","surface_blocked")}function Kk(e,t,n){let r=N(n);if(r.length===0)return null;let o=ze(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return Qt(i,s,r,"command_not_allowlisted","command_blocked")}function Yk(e,t,n){let r=ne(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=ze(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return Qt(i,s,r,"action_not_allowlisted","action_blocked")}function Xk(e,t,n){let r=ne(n);if(r.length===0)return null;let o=ze(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return Qt(i,s,r,"service_not_allowlisted","service_blocked")}function Jk(e,t){let n=ne(t.name);return ze(e,t.name)?.disabled===!0?"extension_override_disabled":Qt(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Qk(e,t){if(e.trustMode==="off")return null;let n=ze(e,t.name),r=ne(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Zk(e,t){if(e.mode==="off")return null;let n=ze(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(n==="none")return null;let r=t.permissions;if(!r)return"sandbox_permissions_missing";let o=i=>r[i]===!0;return n==="restricted"?o("process_spawn")?"sandbox_restricted_disallows_process_spawn":o("env_write")?"sandbox_restricted_disallows_env_write":null:o("process_spawn")?"sandbox_strict_disallows_process_spawn":o("network")?"sandbox_strict_disallows_network":o("fs_write")?"sandbox_strict_disallows_fs_write":o("env_write")?"sandbox_strict_disallows_env_write":null}function Po(e,t,n,r,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${n.layer}:${n.name}:reason=${r}${s}`}function lp(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=Jk(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Qk(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=Zk(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:Po("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:Po("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function up(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=dp(e,t,n);return r?{allowed:e.mode==="warn",warning:Po(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function eA(e,t,n,r,o){let i=typeof r=="string"?dp(e,t,r):null,s=Gk(e,t,n),a=o.command?Kk(e,t,o.command):null,c=o.action?Yk(e,t,o.action):null,d=o.service?Xk(e,t,o.service):null;return i??s??a??c??d}function tA(e,t,n,r){let o={method:ne(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=N(r.command)),r.action&&(o.action=ne(r.action).replace(/\s+/g,"-")),r.service&&(o.service=ne(r.service)),o}function fp(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=eA(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=Po(e.mode==="warn"?"violation":"blocked","registration",t,a,tA(r,n,o,s));return{allowed:e.mode==="warn",warning:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01116a5e-62d1-591b-9fd0-84ac6e99f8d0")}catch{}})();function $o(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function La(){return{overrides:[],handlers:[]}}function Fa(){return{overrides:[]}}function Ua(){return{overrides:[]}}function za(){return{overrides:[]}}function Ha(){return{overrides:[]}}function Ba(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd1de600-27e4-522b-842e-1993c12e9f0e")}catch{}})();var pp=100;function mp(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function nA(e){if(e==null)return;let t=Re(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Va(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function _p(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function yt(e){if(e!=null)return typeof e!="boolean"?null:e}function rA(e){let t=_p(e.priority);return t===void 0?pp:t}function oA(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=Vn(t);return n!==t.trim().toLowerCase()?null:n}function qa(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function iA(e){if(e==null)return;let t=Re(e);if(!t)return null;let n=qa(t.source),r=qa(t.signature),o=qa(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function sA(e){if(e==null)return;let t=Re(e);if(!t)return null;let n=yt(t.fs_read),r=yt(t.fs_write),o=yt(t.network),i=yt(t.env_read),s=yt(t.env_write),a=yt(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function aA(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=Zm(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function cA(e){if(e==null)return;let t=Re(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>N(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function dA(e){let t=_p(e.manifest_version);if(t===null)return null;let n=mp(e,"pm_min_version");if(n===null)return null;let r=mp(e,"pm_max_version");if(r===null)return null;let o=nA(e.engines);if(o===null)return null;let i=yt(e.trusted);if(i===null)return null;let s=oA(e);if(s===null)return null;let a=iA(e.provenance);if(a===null)return null;let c=sA(e.permissions);if(c===null)return null;let d=aA(e.capabilities);if(d===null)return null;let l=cA(e.activation);if(l===null)return null;let u=Or(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:u}}function Wa(e){if(typeof e!="object"||e===null)return null;let t=e,n=Va(t,"name");if(n===null)return null;let r=Va(t,"version");if(r===null)return null;let o=Va(t,"entry");if(o===null)return null;let i=rA(t);if(i===null)return null;let s=dA(t);return s===null?null:{name:n,version:r,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}import{constants as He}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();var hp=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),lA=/^[a-z][a-z0-9_]{0,63}$/u,uA=new Map([[He.errno.EACCES,"EACCES"],[He.errno.EDQUOT,"EDQUOT"],[He.errno.EMFILE,"EMFILE"],[He.errno.ENFILE,"ENFILE"],[He.errno.ENOMEM,"ENOMEM"],[He.errno.ENOSPC,"ENOSPC"],[He.errno.EPERM,"EPERM"],[He.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),fA={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function mA(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&hp.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:uA.get(Math.abs(t.errno))??null}function pA(e,t,n={}){let r=mA(e);if(r===null)return null;if(!lA.test(t))throw new y("Host environment operation labels must be bounded identifiers.",g.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=hp.get(r);return new y(`Host filesystem operation ${t} ${o.summary}.`,g.GENERIC_FAILURE,{code:n.codes?.[o.category]??fA[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function gp(e,t,n={}){try{return await t()}catch(r){throw pA(r,e,n)??r}}import _A from"node:fs/promises";import qn 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]="029e0066-2ef5-5204-92ad-4866321710f4")}catch{}})();async function yp(e,t){let n=qn.dirname(t.manifest_path),r=qn.relative(n,t.entry_path);if(r.startsWith("..")||qn.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=qn.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await gp("extension_module_graph_snapshot",()=>_A.cp(n,o,{recursive:!0,force:!0})),qn.join(o,r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function bp(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return N(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function wp(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47d10c23-88f8-5ba1-bcc2-458f339121a8")}catch{}})();var Mo=ar;function vp(e){let t=e.trim().toLowerCase();return Mo.includes(t)?t:null}function Ep(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Mo)if(sr(t,r,n)!==null)return r;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]="355fe619-e6f3-51d9-b88c-0b57267c25be")}catch{}})();function Op(e){return e==="toon"||e==="json"}function Sp(e){return St.includes(e)}function bt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var kp=Symbol("extension_registration_trace");function Ee(e,t){let n=new TypeError(e);return Object.defineProperty(n,kp,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function Ap(e){return e instanceof Error?e[kp]:void 0}function Wn(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Wn(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Wn(t[r]);return n}return e}function Gn(e){if(Array.isArray(e))return e.map(t=>Gn(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=Gn(t[r]);return n}return e}function Zt(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Wn(t)}function Kn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Gn(t)}function Yn(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>Zt(e,n))}function Y(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Xn(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Ga(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ka(e,t){return N(`${e} ${t}`)}function Jn(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var hA=new Set(["low","medium","high"]),gA=new Set(["number","string_set"]),yA=new Set(["string","number","boolean"]);function Ip(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function bA(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=$(r,n);if(!gA.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(D(`${r}.description`,o.description),o.parameters===void 0)return;let i=$(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;Ip(`${c}.name`,s);let d=$(c,a);if(!yA.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);V(`${c}.required`,d.required),D(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function Tp(e){let t=$("registerAssuranceMeasurementProvider provider",e),n=Ip("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!hA.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=$("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);bA(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4abca948-e9ba-52b5-b63c-a20fc344980a")}catch{}})();var wA=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function jo(e,t){return Yn(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function vA(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Ya(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let n=vA(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Xa(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[r,o]of e.entries()){let i=$(`registerCommand definition.arguments[${r}]`,o),s=Y(`registerCommand definition.arguments[${r}].name`,i.name);if(V(`registerCommand definition.arguments[${r}].required`,i.required),V(`registerCommand definition.arguments[${r}].variadic`,i.variadic),D(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function Lo(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=$(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!wA.has(c)).sort((c,d)=>c.localeCompare(d));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);D(`registerFlags flags[${t}].long`,i),D(`registerFlags flags[${t}].short`,s);let a=pd(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${_d(a.token,a.failure)}`);if(D(`registerFlags flags[${t}].value_name`,r.value_name),D(`registerFlags flags[${t}].description`,r.description),V(`registerFlags flags[${t}].required`,r.required),V(`registerFlags flags[${t}].enabled`,r.enabled),V(`registerFlags flags[${t}].visible`,r.visible),V(`registerFlags flags[${t}].list`,r.list),V(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Du(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Rp(`registerFlags flags[${t}]`,r),EA(`registerFlags flags[${t}]`,r)}}function EA(e,t){if(t.value_validation===void 0)return;if(t.value_validation!=="coerce"&&t.value_validation!=="strict")throw new TypeError(`${e}.value_validation must be "coerce" or "strict" (received ${JSON.stringify(t.value_validation)}).`);if(t.value_validation!=="strict")return;let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),r=n===void 0?null:kr(n);if(r!=="number"&&r!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function Rp(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=kr(n);if(r===null)throw new TypeError(`${e} value_type "${n}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?gd(t.default):[t.default];for(let[i,s]of o.entries())if(!yd(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Cp(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=$(`registerItemFields fields[${t}]`,n);Y(`registerItemFields fields[${t}].name`,r.name);let o=Y(`registerItemFields fields[${t}].type`,r.type);if(vp(o)===null){let i=Ep(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Mo.join(", ")}).${s}`)}V(`registerItemFields fields[${t}].optional`,r.optional)}}function OA(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=$(i,o);Y(`${i}.command`,s.command),Y(`${i}.option`,s.option),V(`${i}.enabled`,s.enabled),V(`${i}.required`,s.required),V(`${i}.visible`,s.visible)}}function SA(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=$(i,o);Y(`${i}.key`,s.key),ot(`${i}.values`,s.values),V(`${i}.required`,s.required),ot(`${i}.aliases`,s.aliases)}}function xp(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=$(r,n);Y(`${r}.name`,o.name),D(`${r}.folder`,o.folder),ot(`${r}.aliases`,o.aliases),ot(`${r}.required_create_fields`,o.required_create_fields),ot(`${r}.required_create_repeatables`,o.required_create_repeatables),OA(t,o.command_option_policies),SA(t,o.options)}}function Np(e){let t=$("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(V("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var Dp=["types","statuses","fields","workflows","config","templates","packages"],kA={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Pp(e){let t=$("registerProfile profile",e);if(Y("registerProfile profile.name",t.name),Y("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let n of Dp){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);kA[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function $p(e){e.summary===void 0&&(e.summary="");for(let t of Dp)e[t]===void 0&&(e[t]=[]);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="45ff820c-32af-5bdb-a570-3059684129ce")}catch{}})();function Mp(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5de5028-f981-599b-8d11-0fc7b07beda4")}catch{}})();function jp(e){return typeof e=="string"?e:String(e)}function Qn(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(n=>Number(n)):null}function Ja(e,t){let n=Qn(e),r=Qn(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function Lp(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=jp(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!Qn(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=Ja(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function Fp(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=jp(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!Qn(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=Ja(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,current:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f1f31504-c958-5bb1-a3b9-5339a09ad876")}catch{}})();function Up(e){return Object.freeze({author:e.author,author_source:e.author_source,principal:e.principal,...e.agent===void 0?{}:{agent:Object.freeze({...e.agent})}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99f2a736-ba4b-57e7-a671-08b30c4aa761")}catch{}})();var AA=5e3;async function Qa(e,t,n){let r=[];for(let o of e)try{await o.run(W(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function IA(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 Za(e,t){let n=[];for(let r of e.beforeMutation??[])try{await TA(r,t)}catch(o){if(t.compensation===void 0)throw o;n.push({guard:`${r.layer}:${r.name}`,code:o.code??"extension_mutation_guard_failed"})}return n}async function TA(e,t){let n,r;try{let o=Promise.resolve().then(()=>e.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:W(t.before),after:t.after===null?null:W(t.after),changed_fields:[...t.changed_fields],actor:Up(t.actor),dry_run:t.dry_run,...t.compensation===void 0?{}:{compensation:Object.freeze({transaction_id:t.compensation.transaction_id,step_id:t.compensation.step_id})},sdk:t.sdk}));o.catch(()=>{}),n=await Promise.race([o,new Promise((i,s)=>{r=setTimeout(()=>{s(new y(`Extension mutation guard ${e.name} timed out before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${e.layer}:${e.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},AA),r.unref?.()})]),IA(n,e,t.operation)}catch(o){throw o instanceof y?o:new y(`Extension mutation guard ${e.name} failed before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${e.layer}:${e.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(r)}}async function ec(e,t){return Qa(e.onWrite,"onWrite",t)}async function tc(e,t){return Qa(e.onRead,"onRead",t)}async function nc(e,t){return Qa(e.onIndex,"onIndex",t)}function RA(e){let t="";e instanceof Error&&typeof e.message=="string"?t=e.message:typeof e=="string"?t=e:typeof e=="object"&&e!==null&&typeof e.message=="string"&&(t=e.message);let n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${Ie(n,r-1)}\u2026`:n}function Fo(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?Ie(n,300):void 0}function CA(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"exit_code"))return;let t=e.exit_code;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return t}async function rc(e,t){let n=N(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,args:W(t.args),options:W(t.options),global:W(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,...t.sdk===void 0?{}:{sdk:t.sdk}});return{handled:!0,result:o,warnings:[],...Object.fromEntries([["exitCode",CA(o)],["errorCode",Fo(o,"code")],["remediation",Fo(o,"remediation")]].filter(i=>i[1]!==void 0))}}catch(o){let i=typeof o=="object"&&o!==null&&"exitCode"in o?o.exitCode:void 0;if(typeof i=="number"&&Number.isFinite(i))throw o;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${r.layer}:${r.name}:${r.command}`],errorMessage:RA(o),...Object.fromEntries([["errorCode",Fo(o,"code")],["remediation",Fo(o,"remediation")]].filter(s=>s[1]!==void 0))},"cause",{value:o,configurable:!0})}}function zp(e){return{handled:!1,result:e.payload,warnings:[]}}function Hp(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Bp(e){return{service:e.service,command:e.command?N(e.command):void 0,args:e.args?W(e.args):void 0,options:e.options?ud(e.options):void 0,global:e.global?fd(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:W(e.payload)}}function xA(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 Vp(e,t){return xA(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 qp(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&se(e,n.payload)}function Wp(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function oc(e,t){let n=Hp(e,t.service);if(n.length===0)return zp(t);let r=[];for(let o of n)try{let i=Bp(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(qp(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Wp(o,Vp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function ic(e,t){let n=Hp(e,t.service);if(n.length===0)return zp(t);let r=[];for(let o of n)try{let i=Bp(t),s=await Promise.resolve(o.run(i));if(qp(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Wp(o,Vp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3abe36f7-3c97-58d2-a56d-b4e0ea958461")}catch{}})();var Gp=null,jA=Object.freeze(xc()),Kp=0;function LA(e=Date.now()){return Kp+=1,`${Kp}-${e}`}function FA(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function UA(e,t){let[n,r]=await Promise.all([vt.realpath(e),vt.realpath(t)]);return Tn(n,r)}function zA(e,t=process.cwd()){return{global:wt.join(rd(t),"extensions"),project:wt.join(e,"extensions")}}async function HA(e){try{return(await vt.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function BA(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function Yp(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function VA(e){let t=new Map;try{let n=JSON.parse(await vt.readFile(wt.join(e,".managed-extensions.json"),"utf8")),r=Re(n)?.entries;if(!Array.isArray(r))return t;for(let o of r){if(typeof o!="object"||o===null)continue;let i=o,s=Yp(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>Yp(l)).filter(l=>l!==void 0),c=Or(i.contributions),d={aliases:[...new Set(a)],...s?{package_name:s}:{},...c?{contributions:c}:{}};typeof i.directory=="string"&&i.directory.trim().length>0&&t.set(`directory:${i.directory.trim()}`,d),typeof i.name=="string"&&i.name.trim().length>0&&t.set(`name:${i.name.trim()}`,d)}}catch{return t}return t}function Xp(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function qA(e,t){let n=[...Xp(e),...Xp(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Jp(e,t,n,r,o){let i=[],s=[],a=[],c=await HA(t),d=await VA(t);for(let l of c){let u=await KA(e,t,l,n,r,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function WA(){return{diagnostics:[],warnings:[],candidates:[]}}function Qp(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function GA(e,t,n,r,o,i,s,a){let c=Hc(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(tp(e,t.name,t.legacy_capability_aliases));for(let d of Qm(t.capabilities))c.push(ep(e,t.name,d));return r?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function KA(e,t,n,r,o,i,s){let a=wt.join(t,n),c=wt.join(a,"manifest.json");if(!await nn(c))return Qp(e,n,c,`extension_manifest_missing:${e}:${n}`);let d,l;try{let Se=JSON.parse(await vt.readFile(c,"utf8"));l=Re(Se),d=Wa(Se)}catch{l=null,d=null}if(!d||!l)return Qp(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=wt.resolve(a,d.entry),f=Tn(a,u),m=f?await nn(u):!1,p=f&&m?await UA(a,u):f,h=FA(d.name,r,o),_=await JA(e,d),b=await QA(e,d,s),E=GA(e,d,l,p,m,_,b,h),j=p&&m&&_.allowed&&b.allowed,X=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:h,status:j?"ok":"warn"},warnings:E,candidate:Xm({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:X,extensionReady:j,enabledForLoad:h})}}async function YA(e){let t=zA(e.pmRoot,e.cwd??process.cwd()),n=Bn(e.settings.extensions.enabled),r=Bn(e.settings.extensions.disabled),o=sp(e.settings),i=ap(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?WA():await Jp("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Jp("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=qA(c.candidates,d.candidates),f=[];for(let m of u){let p={layer:m.layer,name:m.manifest.name,trusted:m.manifest.trusted===!0,provenanceVerified:m.manifest.provenance?.verified===!0,sandboxProfile:m.manifest.sandbox_profile,permissions:m.manifest.permissions&&typeof m.manifest.permissions=="object"?{fs_read:m.manifest.permissions.fs_read,fs_write:m.manifest.permissions.fs_write,network:m.manifest.permissions.network,env_read:m.manifest.permissions.env_read,env_write:m.manifest.permissions.env_write,process_spawn:m.manifest.permissions.process_spawn}:void 0},h=lp(o,p);if(h.warning&&l.push(h.warning),!!h.allowed){for(let _ of m.manifest.capabilities){let b=up(o,p,_);b.warning&&l.push(b.warning)}f.push(BA(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function Uo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function XA(){try{let e=Da(import.meta.url,["../../.."]),t=await vt.readFile(wt.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function t_(){return Gp??=XA(),Gp}function n_(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function JA(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=Lp(t.pm_min_version,await t_()),r=n_(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function QA(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=Fp(t.pm_max_version,await t_(),n),o=n_(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Zp(e){try{let t=await vt.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function ZA(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await yp(t.module_graph_snapshot_root,e));let r=new URL(MA(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[o,i]=await Promise.all([Zp(e.entry_path),Zp(e.manifest_path)]),s=t.reload_token??LA();return r.searchParams.set("pm_ext_reload",s),r.searchParams.set("pm_ext_entry",o),r.searchParams.set("pm_ext_manifest",i),r.href}async function yL(e){let t=await YA(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await ZA(s,e));n.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:Uo(a)})}return{...t,warnings:o,loaded:n,failed:r}}var e_=5e3,eI=2147483647;function tI(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let n=e.deactivate;t.deactivate=n.bind(e)}return t}function r_(e){let t=cl(e);return t?tI(t):null}async function bL(e,t,n={}){let r=nI(n?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(l=>`${l.layer}:${l.name}`)),i=[];for(let l of e.loaded){if(o.has(`${l.layer}:${l.name}`))continue;let u=r_(l.module);!u||typeof u.deactivate!="function"||i.push({extension:l,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:u})=>{try{return await rI(u,r),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:Uo(f)}}})),a=[],c=[],d=0;for(let l of s){if(l.ok){d+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),c.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:d,warnings:a,failed:c}}function nI(e){return typeof e!="number"||e<0?e_:e===0||e===1/0?0:Number.isFinite(e)?Math.min(eI,Math.max(1,Math.floor(e))):e_}async function rI(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function oI(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Ue(r)&&t.add(r)}return t}function x(e,t,n){let r=oI(e);if(r!==null&&!r.has(t))throw Ee(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${n} registration call.`})}function iI(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>fe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function sI(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var sc=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,u){this.#e=t,this.extension=iI(t),this.#n=sI(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=fp(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:Wn(o),hint:i}}registerCommandOverride(t,n){let r=N(t);if(r.length===0)throw Ee("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Ee(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Ee("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Ee("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=N(t.name);if(n.length===0)throw Ee("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Ee(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{Km(t);let o=Ya(n,t.action),i=Pu(t.read_output,n,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=In("registerCommand definition.examples",t.examples),d=In("registerCommand definition.failure_hints",t.failure_hints),l=Xa(t.arguments);t.flags!==void 0&&(x(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(Lo(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:jo("registerCommand definition.flags",t.flags)})));let u={source_version:this.#e.version,read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:c,failure_hints:d,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};s&&(u.description=s),a&&(u.intent=a),this.#t.commands.push(u)}catch(o){let i=Uo(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Ee(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(x(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(x(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=N(Y("registerParser command",t));Xn("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(x(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=bp(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){x(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!Sp(o))throw new TypeError(`registerService service must be one of: ${St.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Xn("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...Mp(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(x(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!Op(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return N(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(x(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=N(Y("registerFlags targetCommand",t));Lo(n);let o=jo("registerFlags flags",n);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:o})}registerItemFields(t){if(x(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Cp(t);let n=Yn("registerItemFields fields",t);if(n.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:n})}registerItemTypes(t){if(x(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;xp(t);let n=Yn("registerItemTypes types",t);if(n.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:n})}registerRelationshipKinds(t){if(x(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let n=ai();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(x(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Np(t);let n=Kn("registerMigration definition",t);this.#t.migrations.push(Jn({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerMigration definition",t)},n))}registerProfile(t){if(x(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=Gn(t);Pp(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:$p(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(x(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(Lo(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:jo(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...r,description:r?.description??o,arguments:r?.arguments??i},a=Ym(t,s,r?.description!==void 0);D(`${t} options.action`,s.action),D(`${t} options.description`,s.description),D(`${t} options.intent`,s.intent);let c=Ya(n,s.action),d=In(`${t} options.examples`,s.examples),l=In(`${t} options.failure_hints`,s.failure_hints),u=Xa(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:d,failure_hints:l,arguments:u},m=s.description?.trim();m&&(f.description=m);let p=s.intent?.trim();return p&&(f.intent=p),this.#t.commands.push(f),a}registerImporter(t,n,r){if(x(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Ga(Y("registerImporter name",t));Xn("registerImporter importer",n);let i=Ka(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n($a(s,o,"import"))})}registerExporter(t,n,r){if(x(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Ga(Y("registerExporter name",t));Xn("registerExporter exporter",n);let i=Ka(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n($a(a,o,"export"));return s?.receipt==="suppress"&&!Cs(c)?ku(c):c}})}registerSearchProvider(t){if(x(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=Kn("registerSearchProvider provider",t);this.#t.search_providers.push(Jn({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(x(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=Kn("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(Jn({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(x(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(Tp(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=Kn("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(Jn({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:Zt("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){x(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(bt("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){x(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(bt("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){x(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(bt("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){x(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(bt("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){x(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(bt("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){x(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(bt("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function aI(e,t,n,r,o,i,s,a,c,d,l){return new sc(e,t,n,r,o,i,s,a,c,d,l)}function cI(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:n,item_fields:r,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function dI(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let d=a.get(c.command)??[];d.push(c),a.set(c.command,d)}for(let c of[...a.keys()].sort((d,l)=>d.localeCompare(l))){let d=a.get(c);if(d.length<=1)continue;let l=d[d.length-1];for(let u of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${u.layer}:${u.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let d of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${d.layer}:${d.name}`)}return t}function lI(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function uI(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var fI=new Set(["output_format"]);function mI(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||fI.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function wL(e){let t=cp(e.policy??jA),n=$o(),r=La(),o=Fa(),i=Ua(),s=za(),a=Ha(),c=Ba(),d=[],l=[];for(let m of e.loaded){let p=r_(m.module);if(!p)continue;let h=d.length,_=Gm({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await p.activate(aI(m,n,r,o,i,s,a,c,l,d,t)),d.length>h&&(_(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(b){_(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let E=Ap(b);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:Uo(b),trace:E})}}let u=[...dI(r),...uI(o),...wp(i),...mI(s),...lI(a)],f=[...new Set([...l,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:cI(c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1a38f8c-8f65-59e2-bddf-ed0606a0f0b5")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da25248-2914-5bc5-aa42-87f677ef4ea8")}catch{}})();function kL(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let r=Promise.all([e,...t]).then(()=>n());return e=r.then(()=>{},()=>{}),r}}}function pI(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.push(o))}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8844150-afb4-5f2e-a005-4cfb8482660c")}catch{}})();var _I={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},o_=":";function i_(e,t){return`${e}${o_}${ac(t)}`}function hI(e){return e.slice(e.indexOf(o_)+1)}function ac(e){return e.trim().toLowerCase()}function gI(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=Jm(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function s_(e){let t=new Map,n=(l,u)=>{for(let f of l){let m=i_(f.layer,f.name),p=t.get(m);p===void 0&&(p=new Set,t.set(m,p)),p.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function yI(e,t={}){let n=s_(e),r=new Set;t.extensionName!==void 0&&r.add(ac(t.extensionName));for(let i of t.extensionNames??[])r.add(ac(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(hI(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function bI(e,t){let n=s_(t),r=[];for(let o of e){let i=gI(o.capabilities);if(i.length===0)continue;let s=n.get(i_(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67666bab-2e73-549c-bf95-ba505143a9b5")}catch{}})();var Et=null,d_=null,vI=null,EI=null,cc=null,OI=null,l_=null,u_=null;var SI=[],f_=new c_;function P(){return f_.getStore()}function PL(e){return f_.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var kI=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function a_(e){let t=Oe.resolve(e);for(;;){if(wI(Oe.join(t,".git")))return t;let n=Oe.dirname(t);if(n===t)return;t=n}}function AI(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=a_(t)??Oe.resolve(t),r=a_(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=Oe.relative(n,Oe.resolve(e)),i=o.length>0&&!o.startsWith(`..${Oe.sep}`)&&o!==".."&&!Oe.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(Oe.sep).join("/")}:{}}}function $L(e){let t=P();if(t){t.hooks=e;return}Et=e}function ML(e){let t=P();if(t){t.commands=e;return}d_=e}function jL(e){let t=P();if(t){t.parsers=e;return}vI=e}function LL(e){let t=P();if(t){t.preflight=e;return}EI=e}function FL(e){let t=P();if(t){t.services=e;return}cc=e}function UL(e){let t=P();if(t){t.renderers=e;return}OI=e}function zL(e){let t=P();if(t){t.registrations=e;return}l_=e}function Uu(){let e=P();return e?e.registrations:l_}function LS(){let e=P(),t=e?e.commandContext:u_;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function HL(e){if(!e)return;let t=P();t?t.affectedItems.push(e):SI.push(e)}function BL(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"||kI.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function m_(e){let t=P(),n=t?t.hooks:Et;return n?ec(n,e):[]}var p_=new c_;function VL(e,t){return!e||(e.beforeMutation?.length??0)===0?t():p_.run(e,t)}function II(){let e=P();return e?e.hooks:Et}async function qL(e){let t=p_.getStore(),n=t??II();if(!n)return;let{resolveMutationActor:r}=await import("./mutation-actor-TCYDPUGG.js"),o=t!==void 0||e.dry_run===!0,i=o?void 0:Na(e.pm_root,[e.before?.metadata.id,e.after?.metadata.id],e.operation),s=await Za(n,{pm_root:e.pm_root,operation:e.operation,before:e.before,after:e.after,changed_fields:e.changed_fields,sdk:e.sdk,actor:r(e.author),dry_run:o,...i===void 0?{}:{compensation:{transaction_id:i.transaction_id,step_id:i.step_id}}});i?.overrides.push(...s.map(a=>({source:"mutation_guard",...a})))}async function Yr(e){let t=P(),n=t?t.hooks:Et;return n?tc(n,e):[]}function WL(){let e=P();return((e?e.hooks:Et)?.onWrite?.length??0)>0}function GL(){let e=P();return((e?e.hooks:Et)?.onRead?.length??0)>0}async function KL(e){let t=P(),n=t?t.hooks:Et;return n?nc(n,e):[]}async function YL(e){let t=P(),n=t?t.commands:d_;return n?rc(n,{...e,...AI(e.pm_root)}):{handled:!1,result:null,warnings:[]}}function __(e,t){let n=P(),r=n?n.commandContext:u_;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 Kt(e,t){let n=P(),r=n?n.services:cc;return r?ic(r,__(e,t)):{handled:!1,result:t,warnings:[]}}function Im(e,t){let n=P(),r=n?n.services:cc;return r?oc(r,__(e,t)):{handled:!1,result:t,warnings:[]}}import zo from"node:fs/promises";import ie 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]="f1eb25ad-08b8-5826-9ec1-7b0a7a22d277")}catch{}})();var g_="lock_path_unsafe";function TI(e,t){return ie.relative(e,t).split(ie.sep).join("/")}function RI(e,t){return e==="lock_entry_symlink"?`Remove the symlinked lock entry ${t} (pm neither follows nor deletes it), then retry the same operation.`:e==="lock_directory_replaced"?`Restore ${t} as a real directory inside the tracker, then retry the same operation. The lock file created while it was replaced stays where the replacement pointed, because pm never deletes outside the tracker; remove it there if it is not wanted.`:"Replace the symlinked or replaced lock directory with a real directory inside the tracker (for example: remove the link, then let pm recreate locks/), then retry the same operation."}function Zn(e){let t=e.component??ie.dirname(e.lockPath),n=TI(e.pmRoot,t);return new y(`Refused to acquire lock ${e.id}: ${n} is not a real directory inside the tracker (${e.reason}). Locks are never created through a symlinked or replaced lock directory.`,g.CONFLICT,{code:"lock_path_unsafe",item_id:e.id,reason:e.reason,lock_component:n,required:RI(e.reason,n)})}function h_(e,t){return e.dev===t.dev&&e.ino===t.ino}async function Ho(e,t,n,r=!0){let o=ie.resolve(e),i=ie.dirname(ie.resolve(t)),s=ie.relative(o,i);if(s===".."||s.startsWith(`..${ie.sep}`)||ie.isAbsolute(s))throw Zn({pmRoot:o,lockPath:t,id:n,reason:"lock_path_outside_tracker",component:i});let a=o,c=null;for(let l of s===""?[]:s.split(ie.sep)){a=ie.join(a,l);let u;try{u=await zo.lstat(a,{bigint:!0})}catch(f){if(r&&B(f))return null;throw f}if(u.isSymbolicLink())throw Zn({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_symlink",component:a});if(!u.isDirectory())throw Zn({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_not_directory",component:a});c={dev:u.dev,ino:u.ino}}if(c!==null)return c;let d=await zo.stat(o,{bigint:!0});return{dev:d.dev,ino:d.ino}}async function y_(e,t,n){let r;try{r=await zo.lstat(t)}catch{return}if(r.isSymbolicLink())throw Zn({pmRoot:e,lockPath:t,id:n,reason:"lock_entry_symlink",component:t})}async function b_(e){let t=await e.handle.stat({bigint:!0}),n={dev:t.dev,ino:t.ino},r=!1;try{let o=await Ho(e.pmRoot,e.lockPath,e.id,!1);if(h_(e.directory,o)){let i=await zo.lstat(e.lockPath,{bigint:!0});r=!i.isSymbolicLink()&&h_(n,i)}}catch{r=!1}if(!r)throw Zn({pmRoot:e.pmRoot,lockPath:e.lockPath,id:e.id,reason:"lock_directory_replaced"})}import dc from"node:fs/promises";import{createHash as CI}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]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();function w_(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function xI(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!w_(t,"ESRCH")}}function v_(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function en(e){try{return v_(await dc.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function On(e=process.pid){let t=await en(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function Sn(e,t,n){if(!xI(e.pid))return!1;let r=await en(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function E_(){try{let[e,t]=await Promise.all([dc.readFile("/proc/sys/kernel/random/boot_id","utf8"),dc.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:CI("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function lc(){let[e,t]=await Promise.all([E_(),en(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function Bo(e){if(!e||typeof e.pid!="number"||!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host_identity!="string"||typeof e.process_start_identity!="string"||!/^\d+$/u.test(e.process_start_identity))return"unknown";let t=await E_();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(r){return w_(r,"ESRCH")?"dead":"unknown"}let n=await en(e.pid);return n===null?"unknown":n===e.process_start_identity?"alive":"dead"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be5b7a07-492a-5ca6-b607-059251a7cea3")}catch{}})();function PI(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:n.host_identity,process_start_identity:n.process_start_identity},warnings:[]}}async function Ot(e,t=!0){try{let n=await H.readFile(e,"utf8");return t&&await Yr({path:e,scope:"project"}),PI(n)}catch(n){return B(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Be(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function $I(e,t,n=process.platform){if(Be(e,"EEXIST"))return!0;if(!Be(e,"EPERM")&&!Be(e,"EACCES")&&!Be(e,"EBUSY"))return!1;try{return await H.lstat(t),!0}catch(r){if(n!=="win32"||!B(r)&&!Be(r,"EPERM")&&!Be(r,"EACCES")&&!Be(r,"EBUSY"))return!1}try{return await H.access(F.dirname(t),NI.W_OK),!0}catch{return!1}}async function I_(e,t){await m_({path:e,scope:"project",op:t})}async function MI(e,t,n,r=Wo()){return{...await lc(),id:e,pid:process.pid,owner:t,token:r,created_at:pn(),ttl_seconds:n}}async function jI(e,t,n,r,o,i,s){let a=await Ho(e,t,n);s&&a===null&&await H.mkdir(F.dirname(t),{recursive:!0});let c=await Xo(t,n);if(c===null)throw await H.access(F.dirname(t)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let d;try{let l=await Ho(e,t,n,!1),u=await H.open(t,"wx");try{await b_({pmRoot:e,lockPath:t,id:n,handle:u,directory:l})}catch(f){throw await u.close(),f}try{try{let f=await MI(n,r,o,i);d=f.created_at,await u.writeFile(`${JSON.stringify(f,null,2)}
|
|
99
|
+
`,"utf8")}finally{await u.close()}}catch(f){throw await mc(t,"lock:release"),f}}finally{await c()}return await I_(t,"lock:create"),d}async function mc(e,t){try{return await H.unlink(e),await I_(e,t),!0}catch{return!1}}async function LI(e,t,n,r){let o=performance.now(),i=Go;for(;;){let s=await Xo(e,t);if(s!==null){try{let d=await Ot(e,!1);uc(d.info,t,n,r)&&await mc(e,"lock:release")}finally{await s()}return}let a=await Ot(e,!1);if(!uc(a.info,t,n,r))return;let c=performance.now()-o;if(c>=Vo)return;await Yo(Math.min(i,Vo-c)),i=Math.min(i*2,Ko)}}function uc(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function pc(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}async function T_(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await Bo(e)==="dead"}async function R_(e,t){return pc(e,t)||await T_(e)}async function uu(e,t,n){let{info:r}=await Ot(mi(e,t),!1);return r!==null&&r.owner.startsWith(n)&&!await R_(r,r.ttl_seconds)}function FI(e){return e?.owner?` (owner ${e.owner})`:""}var Go=25,Ko=200,C_=250,UI=12e4,zI=3,HI=".stale-cleanup",x_="owner.json",N_=1e4,Vo=N_+Ko;function fc(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 BI(e){let t=process.env.PM_LOCK_WAIT_MS,n=fc(t);if(n!==void 0)return n;let r=fc(e);return r!==void 0?r:0}function VI(e,t){return Math.min(BI(e),t??1/0)}function Yo(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}async function D_(e,t,n,r=0){n=Math.floor(n);let o=await Bo(t),i=r>0?` across ${r} owner handoff(s)`:"",s=n>0?` after waiting ${n}ms${i}`:"";return new y(`Item ${e} is locked${FI(t)} (owner process ${o})${s}`,g.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:C_,...n>0?{waited_ms:n,owner_handoffs:r}:{}}})}function qI(e,t){let n=performance.now(),r=n,o,i=0;return{startedAtMs:n,observe(s){let a=performance.now(),c=GI(s);o!==void 0&&c!==o&&(i+=1,r=a),o=c;let d=a-n,l=a-r;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function WI(e,t,n){return n!=="progress"||t!==void 0?e:Math.max(e,UI)}function GI(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function KI(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function YI(e,t,n,r){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(r==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=n===null?"the lock no longer exists":`it is now held by ${n.owner} since ${n.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function O_(e,t,n,r){let{summary:o,required:i}=YI(e,t,n,r);return new y(`${o} Nothing was written.`,g.CONFLICT,{code:"lock_lost",item_id:e,reason:r,lease:KI(t),current_owner:n===null?null:{owner:n.owner,pid:n.pid,created_at:n.created_at,ttl_seconds:n.ttl_seconds},required:i,recovery:{retry_after_ms:C_}})}async function XI(e,t){let n=performance.now(),r=Go;for(;;){let o=await Xo(e,t);if(o!==null)return o;let i=performance.now()-n;if(i>=Vo)return null;await Yo(Math.min(r,Vo-i)),r=Math.min(r*2,Ko)}}async function JI(e,t,n,r){let o=await XI(e,t);if(o===null){let i=await Ot(e,!1);throw O_(t,n,i.info,"fence_gate_unavailable")}try{let i=await Ot(e,!1);if(!uc(i.info,t,n.owner,n.token))throw O_(t,n,i.info,i.info===null?"lease_released":"lease_taken_over");return await r()}finally{await o()}}function QI(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}async function ZI(e,t,n){let r=F.dirname(F.dirname(e)),o=`Remove ${t} under ${F.relative(process.cwd(),r)||"."} once its owner is confirmed gone, then retry the same command.`;if(!n)return`${o} pm gc --scope locks keeps this lock: its metadata cannot be read or dated, or its own TTL has not run out.`;try{await H.access(_r(r))}catch{return o}let i=process.cwd(),s=F.resolve(hr(i))===F.resolve(r)?[]:["--pm-path",F.relative(i,r)||"."];return`Run ${oe([...s,"gc","--scope","locks"])} (add --dry-run to preview), then retry the same command.`}function eT(e){return e.info!==null&&e.warnings.length===0&&Number.isFinite(Date.parse(e.info.created_at))&&pc(e.info,e.info.ttl_seconds)}async function tT(e,t,n,r,o){if(!r&&o){let i=n.warnings.length>0?` (${n.warnings.join(",")})`:"",s=`locks/${F.basename(t)}`;throw new y(`Lock ${e} is stale${i}; remove the expired lease, or rerun with --force where this command accepts it`,g.CONFLICT,{code:"stale_lock_requires_override",details:{lock_id:e,lock_path:s},why:`The lease in ${s} is past its TTL, and force_required_for_stale_lock keeps an expired lease until it is removed explicitly.`,required:"Remove the expired lease, then retry the same command.",nextSteps:[await ZI(t,s,eT(n))]})}}function nT(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,host_identity:n.host_identity,...typeof i=="string"?{process_start_identity:i}:{}}}async function qo(e){try{return nT(await H.readFile(F.join(e,x_),"utf8"))}catch(t){return B(t)?null:void 0}}async function _c(e){try{return await H.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function S_(e,t){let n=await qo(e);for(let r=0;n===void 0&&r<3;r+=1)await Yo(Go),n=await qo(e);!n||n.token!==t||await _c(e)}async function k_(e){try{await H.mkdir(e)}catch(n){return Be(n,"EEXIST"),null}let t={...await On(),host_identity:(await lc()).host_identity,token:Wo()};try{await H.writeFile(F.join(e,x_),`${JSON.stringify(t)}
|
|
100
|
+
`,"utf8")}catch{return await _c(e),null}return t}async function A_(e,t){let n=F.join(F.dirname(e),"recoveries"),r=DI("sha256").update(t).digest("hex");try{return await H.mkdir(n,{recursive:!0}),(await qo(e))?.token!==t?!1:(await H.rename(e,F.join(n,`gate-${r}`)),!0)}catch{return!1}}async function rT(e){let t;try{let r=await H.stat(e);t=Date.now()-r.mtimeMs}catch(r){return B(r)}let n=await qo(e);if(n===void 0)return!1;if(n!==null){if(await Bo(n)==="dead")return A_(e,n.token);if(n.host_identity!==void 0)return!1}return t<=N_||n!==null&&await Sn(n,t,Number.POSITIVE_INFINITY)?!1:n!==null?A_(e,n.token):_c(e)}async function Xo(e,t){let n=`${e}${HI}`,r=await k_(n);if(r!==null)return async()=>S_(n,r.token);if(!await rT(n))return null;let o=await k_(n);return o===null?null:async()=>S_(n,o.token)}async function oT(e,t){let n=F.join(F.dirname(e),"recoveries");await H.mkdir(n,{recursive:!0}),await H.writeFile(F.join(n,`${Wo()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:pn(),lock:JSON.parse(t)})}
|
|
101
|
+
`,{encoding:"utf8",flag:"wx",mode:384})}async function iT(e){let t=await Xo(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await Ot(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};let r=await T_(n.info);if(!pc(n.info,e.ttlSeconds)&&!r)return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(await tT(e.id,e.lockPath,n,e.force||r,e.forceRequiredForStaleLock),e.staleRemovals>=zI)throw await D_(e.id,n.info,performance.now()-e.startedAtMs);return r&&await oT(e.lockPath,JSON.stringify(n.info)),{lockInfo:n,shouldRetryCreate:await mc(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function sT(e,t,n,r){if(e instanceof y&&e.code===g_)throw e;if(!await $I(e,n))throw new y(`Failed to acquire lock for ${r}: ${al(e)}`,g.GENERIC_FAILURE);await y_(t,n,r)}async function kn(e,t,n,r,o=!1,i=!0,s,a={}){return(await hc(e,t,n,r,o,i,s,a)).release}async function hc(e,t,n,r,o=!1,i=!0,s,a={}){let c=fc(a.maxWaitMs),d=await Kt("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let E=QI(d.result);if(E)return{release:async()=>{await Promise.resolve(E()),await Kt("lock_release",{pm_root:e,id:t,owner:r})},fence:j=>j()}}let l=mi(e,t),u=VI(s,c),f=WI(u,c,a.waitPolicy),m=qI(u,f),p=m.startedAtMs,h=0,_=Go,b=Wo();for(;;)try{let E=await jI(e,l,t,r,n,b,a.createParentDirectories!==!1),j={owner:r,token:b,acquiredAt:E,ttlSeconds:n};return{release:async()=>{await LI(l,t,r,b),await Kt("lock_release",{pm_root:e,id:t,owner:r})},fence:X=>JI(l,t,j,X)}}catch(E){await sT(E,e,l,t);let j=await Ot(l);if(await R_(j.info,n)){let Se=await iT({lockPath:l,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:h,waitBudgetMs:u,startedAtMs:p,fallbackLockInfo:j});if(j=Se.lockInfo,Se.staleRemovalCounted&&(h+=1),Se.shouldRetryCreate)continue}let X=m.observe(j.info);if(X.exhausted)throw await D_(t,j.info,u===0?0:X.elapsedMs,X.ownerHandoffs);await Yo(Math.min(_,X.remainingMs)),_=Math.min(_*2,Ko)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b86f3679-07fa-5566-b8cb-fb05ab89dd31")}catch{}})();var cT="session.json";function yc(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function M_(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=yc(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=>yc(c,128)),a=t.focused_item_id===void 0||yc(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function dT(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=M_(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function bc(e){return ue.join(od(e),cT)}async function j_(e){try{let t=await $_.readFile(bc(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=dT(r.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function wc(e,t){let n=await hc(e,"session-state",ti.locks.ttl_seconds,"session-state",!1,!1,ti.locks.wait_ms);try{let r=await j_(e);t(r);let o=bc(e);await n.fence(async()=>{await $_.mkdir(ue.dirname(o),{recursive:!0}),await $c(o,JSON.stringify(r))})}finally{await n.release()}}function vc(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${P_("sha256").update(e).digest("hex").slice(0,24)}`}function Ec(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Oc(e){let t=[...new Set(e)].sort((r,o)=>r.localeCompare(o));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${P_("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Sc(e,t,n){await wc(e,r=>{let o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete r.semantic_attribution:r.semantic_attribution=o})}async function DF(e){let t=vc(e.principal);await Sc(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??Oc(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Ec([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function PF(e){let t=vc(e.principal);await Sc(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??Oc(r),confidence:o?"high":"medium",evidence:Ec([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function $F(e){let t=vc(e.principal);await Sc(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??Oc(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Ec([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function lT(e,t){let n=t.PM_PATH?.trim();if(n){let o=ue.resolve(e,n);if(gc(ue.join(o,"settings.json")))return o;let i=ue.join(o,".agents","pm");if(gc(ue.join(i,"settings.json")))return i}let r=ue.resolve(e);for(let o=0;o<32;o+=1){let i=ue.join(r,".agents","pm");if(gc(ue.join(i,"settings.json")))return i;let s=ue.dirname(r);if(s===r)break;r=s}}function kl(e){if(!e.key)return;let t=lT(e.cwd,e.env);if(t)try{let n=JSON.parse(aT(bc(t),"utf8"));return M_(n.semantic_attribution?.[e.key])}catch{return}}async function MF(e){return(await j_(e)).focused_item}async function jF(e,t){await wc(e,n=>{n.focused_item=t})}async function LF(e){await wc(e,t=>{delete t.focused_item})}export{sr as a,Jm as b,Ma as c,zk as d,Hk as e,N as f,F_ as g,jc as h,kt as i,Lc as j,ar as k,Fc as l,Uc as m,fT as n,mT as o,pT as p,cr as q,dr as r,_T as s,hT as t,gT as u,yT as v,bT as w,wT as x,lr as y,rn as z,ni as A,vT as B,zc as C,ET as D,OT as E,ST as F,kT as G,vp as H,Mg as I,Sr as J,VR as K,pd as L,_d as M,Lp as N,Fp as O,z_ as P,H_ as Q,ri as R,si as S,ai as T,xT as U,NT as V,DT as W,J_ as X,Bc as Y,PT as Z,Tn as _,Da as $,NM as aa,Eb as ba,px as ca,_x as da,hx as ea,al as fa,gx as ga,yx as ha,bx as ia,wx as ja,Wc as ka,ih as la,Kc as ma,Zc as na,BT as oa,ui as pa,gh as qa,VT as ra,xh as sa,Nh as ta,qT as ua,WT as va,nR as wa,hr as xa,nd as ya,rd as za,_r as Aa,rR as Ba,oR as Ca,iR as Da,mi as Ea,od as Fa,A as Ga,se as Ha,At as Ia,We as Ja,og as Ka,sd as La,pi as Ma,ag as Na,cg as Oa,yr as Pa,cd as Qa,lg as Ra,mg as Sa,mR as Ta,pR as Ua,gg as Va,yg as Wa,bg as Xa,wg as Ya,_i as Za,hR as _a,vg as $a,cn as ab,br as bb,gR as cb,yR as db,bR as eb,Eg as fb,Og as gb,Sg as hb,SR as ib,kR as jb,kg as kb,wr as lb,AR as mb,IR as nb,Ag as ob,Ig as pb,Tg as qb,ld as rb,It as sb,Rg as tb,TR as ub,RR as vb,CR as wb,xR as xb,NR as yb,DR as zb,PR as Ab,$R as Bb,Ke as Cb,Or as Db,UR as Eb,$o as Fb,La as Gb,Fa as Hb,Ua as Ib,za as Jb,Ha as Kb,Ba as Lb,Wa as Mb,gp as Nb,kr as Ob,GR as Pb,gd as Qb,KR as Rb,Ie as Sb,XR as Tb,JR as Ub,QR as Vb,LA as Wb,UA as Xb,zA as Yb,YA as Zb,yL as _b,bL as $b,wL as ac,Rr as bc,Te as cc,yi as dc,wd as ec,ae as fc,wi as gc,mn as hc,_e as ic,fC as jc,mC as kc,pC as lc,Rd as mc,vi as nc,Cd as oc,xd as pc,_C as qc,Nd as rc,Dd as sc,Ei as tc,Pd as uc,gC as vc,$d as wc,yC as xc,Md as yc,vC as zc,Ay as Ac,jd as Bc,re as Cc,ce as Dc,kC as Ec,pn as Fc,he as Gc,_n as Hc,Tt as Ic,G as Jc,xC as Kc,NC as Lc,Hd as Mc,oe as Nc,Ti as Oc,Ri as Pc,Vd as Qc,FC as Rc,Rt as Sc,UC as Tc,Wd as Uc,zC as Vc,rb as Wc,YC as Xc,ib as Yc,XC as Zc,Zd as _c,$r as $c,el as ad,hn as bd,fb as cd,JC as dd,QC as ed,Ci as fd,xi as gd,ex as hd,Ni as id,nl as jd,mb as kd,tx as ld,jr as md,_b as nd,ix as od,Di as pd,ax as qd,cx as rd,gb as sd,yb as td,dx as ud,il as vd,Lr as wd,jx as xd,Xb as yd,mw as zd,Hr as Ad,Lx as Bd,Fx as Cd,Pt as Dd,Xe as Ed,Gi as Fd,Hx as Gd,Bx as Hd,Ho as Id,Bo as Jd,XI as Kd,Xo as Ld,oT as Md,kn as Nd,hc as Od,bc as Pd,j_ as Qd,vc as Rd,DF as Sd,PF as Td,$F as Ud,MF as Vd,jF as Wd,LF as Xd,Zi as Yd,es as Zd,Rl as _d,tN as $d,nN as ae,rN as be,oN as ce,iN as de,sN as ee,os as fe,Pl as ge,aN as he,cN as ie,dN as je,mv as ke,$l as le,Ml as me,lN as ne,uN as oe,Kr as pe,bN as qe,pv as re,wN as se,vN as te,Ll as ue,Xr as ve,kN as we,cs as xe,ds as ye,vv as ze,Bl as Ae,MN as Be,Jr as Ce,Vl as De,jN as Ee,LN as Fe,Wl as Ge,ms as He,vn as Ie,FN as Je,Nv as Ke,Dv as Le,Ql as Me,jv as Ne,UN as Oe,zN as Pe,HN as Qe,jt as Re,nu as Se,aE as Te,fE as Ue,sD as Ve,aD as We,ok as Xe,Co as Ye,et as Ze,En as _e,Gt as $e,Z$ as af,ka as bf,eM as cf,Zr as df,hs as ef,Aa as ff,eu as gf,tM as hf,nM as if,rM as jf,mM as kf,pM as lf,_M as mf,hM as nf,gM as of,yM as pf,bM as qf,wM as rf,Ok as sf,Sk as tf,kk as uf,vM as vf,xk as wf,EM as xf,OM as yf,SM as zf,kM as Af,Na as Bf,AM as Cf,IM as Df,kL as Ef,pI as Ff,_I as Gf,ac as Hf,yI as If,bI as Jf,PL as Kf,AI as Lf,$L as Mf,ML as Nf,jL as Of,LL as Pf,FL as Qf,UL as Rf,zL as Sf,Uu as Tf,LS as Uf,HL as Vf,BL as Wf,m_ as Xf,VL as Yf,II as Zf,qL as _f,Yr as $f,WL as ag,GL as bg,KL as cg,YL as dg,Kt as eg,Nu as fg,wD as gg,vD as hg,ED as ig,Hu as jg,Bu as kg,CD as lg,HD as mg,BD as ng,m0 as og,rP as pg,sf as qg,p0 as rg,O0 as sg,k0 as tg,af as ug,A0 as vg,I0 as wg,cf as xg,at as yg,df as zg,oP as Ag,iP as Bg,Ws as Cg,sP as Dg,aP as Eg,cP as Fg,dP as Gg,lP as Hg,GD as Ig,xn as Jg,ee as Kg,be as Lg,Pn as Mg,bP as Ng,ct as Og,FP as Pg,UP as Qg,H0 as Rg,we as Sg,zP as Tg,HP as Ug,BP as Vg,kf as Wg,Y0 as Xg,VP as Yg,If as Zg,Zs as _g,jf as $g,dt as ah,bO as bh,wO as ch,Lf as dh,bo as eh,ea as fh,lt as gh,c1 as hh,d1 as ih,jn as jh,ta as kh,oa as lh,l1 as mh,DO as nh,u1 as oh,f1 as ph,ve as qh,L as rh,S1 as sh,Un as th,VO as uh,k1 as vh,A1 as wh,qO as xh,I1 as yh,T1 as zh,R1 as Ah,YO as Bh,tm as Ch,XO as Dh,B1 as Eh,QO as Fh,rm as Gh,V1 as Hh,sm as Ih,nS as Jh,aa as Kh,mS as Lh,AS as Mh,mm as Nh,X1 as Oh,r$ as Ph,o$ as Qh,Ju as Rh,T$ as Sh,Dn as Th,ye as Uh,gP as Vh,Ks as Wh,go as Xh,mf as Yh,Ys as Zh,pf as _h};
|
|
102
|
+
//# sourceMappingURL=chunk-UWS3FC4D.js.map
|